java 解析xml文档之w3c模式解析demo

public class W3cTest {

 /**
  解析xml的几种方法
  */
 public static void main(String[] args) {
  System.out.println("执行!");
  try {
   creatXml();
  } catch (Exception e) {
   e.printStackTrace();
  }
  try {
   resolving();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 //创建xml文档并创建节点
 public static void creatXml() throws Exception{
  //创建 解析器工厂
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  //创建 xml解析器
  DocumentBuilder db = dbf.newDocumentBuilder();
  //获取要操作的document对象
  Document doucment = db.newDocument();
  //设置xml版本
  doucment.setXmlVersion("1.0");
  //创建跟节点
  Element root = doucment.createElement("heros");
  //将根节点添加到doc对象
  doucment.appendChild(root);
  //声明 数组
  String nameList[] = {"李奇微","麦克阿瑟","周笔畅","刘德华","赵本山","刘能","曹操"};
  String sexList[] = {"男","女"};
  //循环写入数据
  for (int i = 0; i < 20; i++) {
   //创建根节点元素
   Element rootElement = doucment.createElement("hreo");
   //声明参数
   String id = "";
   //生成9位的随机id
   for (int j = 0; j < 9; j++) {
    id += new Random().nextInt(8)+1;
   }
   //设置元素节点的属性
   rootElement.setAttribute("id", id);
   //添加元素到根节点中
   root.appendChild(rootElement);
   //设置元素节点
   Element name = doucment.createElement("姓名");
   Element sex = doucment.createElement("性别");
   Element age = doucment.createElement("age");
   //给元素节点赋值
   name.setTextContent(nameList[new Random().nextInt(nameList.length)]);
   sex.setTextContent(sexList[new Random().nextInt(sexList.length)]);
   age.setTextContent(new Random().nextInt(20)+20+"");
   String tel = "";
   for(int k = 0 ; k < 7 ; k++){
    tel += new Random().nextInt(9);
   }
   //添加节点到元素节点中
   rootElement.appendChild(name);
   rootElement.appendChild(sex);
   rootElement.appendChild(age);
  }
  //把doucment 映射到文件
  TransformerFactory tff = TransformerFactory.newInstance();
  Transformer tf = tff.newTransformer();
  //生成xml文件
  File file = new File("d:\\abc\\w3c.xml");
  //判断有文件,没有就创建
  if(file.exists()){
   file.createNewFile();
  }
  //设置是否添加空格
  tf.setOutputProperty(OutputKeys.INDENT,"yes");
  //输出文件格式!!!
  tf.setOutputProperty(OutputKeys.ENCODING, "utf-8");
  //输出文件
  tf.transform(new DOMSource(doucment), new StreamResult(new FileOutputStream(file)));
  
  //测试输出xml文件路径
  System.out.println(file.getAbsolutePath());
  
 }

猜你喜欢

转载自my.oschina.net/u/2282777/blog/675570