Java 的XML读取(应用DOM+xPath)

  以下面的math.xml文件作为示例xml文件。文件为一次考试的数学成绩,内含学生lzxzj的成绩。

 

------------- math.xml-------------

<Math>  

    <student id="1">

        <name>zj</name>

        <score>87</score>

    </student> 

    <student id="2">

        <name>lzx</name>

        <score>85</score>

    </student>  

</Math>

-------------------------------------

进行如下操作:

 

1.读取math.xml至内存

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = dbf.newDocumentBuilder();

File f = new File("d:""math.xml");

Document doc = db.parse(f);

 

2.获得student节点列表

XPathFactory xpathFactory=XPathFactory.newInstance();

XPath xpath=xpathFactory.newXPath();

NodeList list=(NodeList)xpath.evaluate("math/student",doc,

XPathConstants.NODESET);

 

3.获得节点为student的第一个节点

XPathFactory xpathFactory=XPathFactory.newInstance();

XPath xpath=xpathFactory.newXPath();

Node node=(Node)xpath.evaluate("math/student",doc,

XPathConstants.NODE);

 

复杂功能皆可根据DOM树结构和xPath路径来实现。

xPath语法:http://www.w3school.com.cn/xpath/xpath_syntax.asp

posted @ 2009-05-16 23:27  因是因非  阅读(972)  评论(0编辑  收藏  举报