您的位置:首页 > 其它

XML的3种解析方式

2016-05-22 15:14 239 查看
Dom4j解析

(1) Dom4j

//创建解析器

SAXReader saxReader = newSAXReader();

//通过解析器的read方法将xml文件 读取到Document对象

Document doc =saxReader.read("要读取的.xml");

//获取XML文件的根节点:students

Element root = doc.getRootElement();

//开始遍历根节点students

for(Iterator<Element> iter =root.elementIterator(); iter.hasNext();){

//student子节点

Element studentEle = iter.next();

for(Iterator<Element> iterator= studentEle.elementIterator();iterator.hasNext();){

Element elts = iterator.next();

String value = elts.getText();

System.out.println(value);

}

}

这是我的XML文件,可以对比理解

<?xmlversion="1.0" encoding="UTF-8"?>
<students>
<student>
<name>吴飞</name>
<college>java学院</college>
<telephone>62354666</telephone>
<notes>男,1982年生,硕士,现就读于北京邮电大学</notes>
</student>
<student>
<name>李雪</name>
<college>C++学院</college>
<telephone>62358888</telephone>
<notes>男,1987年生,硕士,现就读于中国农业大学</notes>
</student>
<student>
<name>Jack</name>
<college>PHP学院</college>
<telephone>66666666</telephone>
<notes>我是澳洲人</notes>
</student>
<student>
<name>Lucy</name>
<college>Android学院</college>
<telephone>88888888</telephone>
<notes>我是美国人</notes>
</student>
</students>

(2) Dome4jXpath

//创建解析器

SAXReader reader = new SAXReader();

//通过解析器的read方法将xml文件读取到Document对象中。

Document doc =reader.read("sys-config.xml");

//driver- > name

//config-> database -> info -> driver -> name

String driverNameXpath =("/config/database-info/driver-name");

Element driverNamePath =(Element)doc
4000
.selectSingleNode(driverNameXpath);

String driverName =driverNamePath.getStringValue();

System.out.println(driverName);

//url

Element urlNamePath = (Element)doc.selectSingleNode("//url");

String url =urlNamePath.getStringValue();

System.out.println(url);

//user:

Element userNamePath = (Element)doc.selectSingleNode("//user");

String user=userNamePath.getStringValue();

System.out.println(user);

//password

Element passwordPath = (Element)doc.selectSingleNode("//password");

String password  = passwordPath.getStringValue();

System.out.println(password);

这是我的xml文件,对比的看更好理解
<?xml version="1.0" encoding="UTF-8"?>

<config>
<database-info>
<driver-name>com.mysql.jdbc.Driver</driver-name>
<url>jdbc:mysql://x.x.x.x:8080/yy</url>
<user>root</user>
<password>123</password>
</database-info>
</config>
(3)Dome4jXpath

//创建解析器

SAXReader reader = new SAXReader();

//通过解析器的read方法  将xml文件读取到Document 对象中

Document doc =reader.read("server.xml");

//connecrtor:server-> service -> connector

Element connElt = (Element)doc.selectSingleNode("/server/service/connector");

//获取port属性对象

Attribute portAttr =connElt.attribute("port");

//获取port属性对象的值

String port =portAttr.getStringValue();

System.out.println(port);

这是我的xml文件,对比的看更好理解

<?xmlversion="1.0" encoding="UTF-8"?>

<server>
<service>
<connector port="8080">
</connector>
</service>
</server>
SAX

 //创建解析工厂

SAXParserFactory parserFactory =SAXParserFactory.newInstance();

//创建解析器

SAXParser parser =parserFactory.newSAXParser();

//通过解析器的parser方法

parser.parse("person.xml",new myDefaultHandler());

class myDefaultHandler extends DefaultHandler{
 @Override 
 publicvoid startElement(String uri, String localName, String qName Attributesattributes) throws             SAXException {
System.out.print("<"+qName+">")
 }
  @Override
  publicvoid characters(char[] ch, int start, int length)throwsSAXException {
System.out.print(newString(ch,start,length));
}

@Override

publicvoid endElement(String uri, String localName, String qName)
throwsSAXException {
  System.out.print("</"+qName+">");
    }        
    }
 这是我的xml文件,对比的看更好理解
<?xmlversion="1.0" encoding="UTF-8"?>
<person>
<p1>
<name>zhangsan</name>
<age>20</age>
</p1>
<p1>
<name>wangwu</name>
<age>29</age>
</p1>
</person>

Xpath

//获取解析工厂

DocumentBuilderFactorybuilderFactory = DocumentBuilderFactory.newInstance();

//获取解析器

DocumentBuilder builder =builderFactory.newDocumentBuilder();

//通过解析器的parser方法将xml文件读取到Document(org.w3c.Document)对象中

Document doc =builder.parse("books.xml");

//获取XPath对象

XPath xpath =XPathFactory.newInstance().newXPath();

//获取bookstore节点下book属性,category值为web下的第二个title节点的文本内容

//bookstore -> book[@categor='web'][2] -> title ->text()

String titleXpath ="/bookstore/book[@category='web'][2]/title/text()";

String title = (String)xpath.evaluate(titleXpath,doc,XPathConstants.STRING);

System.out.println(title);

//获取bookstore节点下book属性 category 值为 web 的title 属性的uk 节点内容

//bookstore- > book[@category='web'] -> title[@lang='uk']

String ukTitleXpath ="/bookstore/book[@category='web']/title[@lang='uk']/text()";

String ukTitle= (String)xpath.evaluate(ukTitleXpath,doc,XPathConstants.STRING);

System.out.println(ukTitle);

//获取bookstore下的 book 属性 category 值为 cooking 的 title 的 lang 属性的值

//bookstore->book[category='cooking']-> title -> @lang

String langXpath="/bookstore/book[@category='cooking']/title/@lang";

String langValue = (String)xpath.evaluate(langXpath,doc,XPathConstants.STRING);

System.out.println(langValue);

//获取bookstore节点下的所有book

//bookstore-> book

NodeList books = (NodeList)xpath.evaluate("/bookstore/book",doc,XPathConstants.NODESET);

//开始遍历books

for(inti=0;i<books.getLength();i++){

//获取到book节点

Nodebook = books.item(i);

StringinnerTitle = (String)xpath.evaluate("title/text()",book,XPathConstants.STRING);

System.out.println(innerTitle);

Stringauthor = (String)xpath.evaluate("author/text()",book,XPathConstants.STRING);

System.out.println(author);

}

这是我的xml文件,对比的看更好理解

<?xmlversion="1.0" encoding="UTF-8"?>
<bookstore>
<!--
获取bookstore 节点下 book 属性 category 值为 web 下的第二个 title 节点的文本内容
获取bookstore 节点下 book 属性 category 值为 web 的 titile 属性为 en 的节点内容
获取bookstore 下 book 属性 category 值为 cooking 的 title 的 lang 属性的值
-->
<book category="children">
<titlelang="en">Harry Potter</title>
<author>JK. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="cooking">
<titlelang="en">Everyday Italian</title>
<author>GiadaDe Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<bookcategory="web">
<titlelang="en">Learning XML</title>
<author>ErikT. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<bookcategory="web">
<titlelang="uk">XQuery Kick Start</title>
<author>JamesMcGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
</bookstore>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  xml 对象 dom