亲宝软件园·资讯

展开

Java解析xml Java实现解析并生成xml原理实例详解

htj10 人气:0

XML解析:

xml解析思想:

Document
Element
Text
Attribute
Comment

* SAX:逐行读取,基于事件驱动
* 优点:不占内存,速度快
* 缺点:只能读取,不能回写

xml常用的解析器:

1.导入jar包 dom4j.jar

2.创建解析器

SAXReader reader = new SAXReader();

3.解析xml 获得document对象

Document document = reader.read(url);

使用步骤:

1、注意:要导包 jaxen...jar

2、创建解析器

SAXReader reader = new SAXReader();

3、解析xml 获得document对象

Document document = reader.read(url);

* 解析XML:

// 1、得到某个具体的节点内容:第2本书的书名--》葵花宝典

// 2、遍历所有元素节点

XPath:

例子:

/* demo.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book name="Harry Potter">
    <author>J.K. Rowling</author>
    <price>29.90$</price>
  </book>
  <book name="冰与火之歌">
    <author>马丁</author>
    <price>28.90$</price>
  </book>
</books>
*/
@Test
public void test1() throws DocumentException{
  SAXReader reader = new SAXReader();
  Document doc = reader.read("./src/demo.xml");
  Element root = doc.getRootElement();
  Element book1 = root.element("book");
  System.out.println(book1.getPath());
  System.out.println(book1.elementText("price"));
  List<?> list = root.elements("book");
  Element book2 = (Element) list.get(1);
  System.out.println(book2.attributeValue("name"));
  for(Iterator<?> it = book1.elementIterator();it.hasNext() ; ){
    Element ele = (Element) it.next();
    System.out.println(ele.getName()+" : "+ele.getText());
  }
}

@Test 
public void test2() throws Exception{//使用 XPath,只用于快速查询,需要用jaxen...jar包
  SAXReader reader = new SAXReader();
  Document doc = reader.read(new File("src/demo.xml"));
  Node node = doc.selectSingleNode("/books/book[2]/author");//需要jaxen.jar包
  String s = node.getText();
  System.out.println(s);
  node = doc.selectSingleNode("/books/book[2]/@name");
  s = node.getText();
  System.out.println(s);
  
  List<Node> booknames = doc.selectNodes("/books//@name");
  for (Node node1 : booknames) {
    System.out.println(node1.getText());
  }
  
  List<?> nodes = doc.selectNodes("/books/*/*");
  for (int i=0; i<nodes.size(); ++i){
    Node node1 = (Node) nodes.get(i);
    System.out.println(node1.getName() + ": " + node1.getText());
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论