解析节点内部的XML

chinna_82

XML格式

<?xml version="1.0"?>
<Employees>
    <Employee emplid="1111" type="admin">
        <firstname>John</firstname>
        <lastname>Watson</lastname>
        <age>30</age>
        <email>[email protected]</email>
    </Employee>
    <Employee emplid="2222" type="admin">
        <firstname>Sherlock</firstname>
        <lastname>Homes</lastname>
        <age>32</age>
        <email>[email protected]</email>
    </Employee>
    <Employee emplid="3333" type="user">
        <firstname>Jim</firstname>
        <lastname>Moriarty</lastname>
        <age>52</age>
        <email>[email protected]</email>
    </Employee>
    <Employee emplid="4444" type="user">
        <firstname>Mycroft</firstname>
        <lastname>Holmes</lastname>
        <age>41</age>
        <email>[email protected]</email>
    </Employee>
</Employees>

代码

FileInputStream file = new FileInputStream(new File("/Users/Desktop/employees.xml"));                 
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();             
DocumentBuilder builder =  builderFactory.newDocumentBuilder();             
Document xmlDocument = builder.parse(file); 
XPath xPath =  XPathFactory.newInstance().newXPath();   
System.out.println("*************************");
String expression = "/Employees/Employee/firstname";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
}

通过使用上面的代码,我设法获取了John,Sherlock,Jim,Mycroft如果我想得到我该怎么办emplid="1111" type="admin" John,emplid="2222" type="admin" Sherlock,emplid="3333" type="user" Jim,emplid="4444" type="user" Mycroft任何建议或参考链接都将受到高度赞赏。

斯穆特耶

看看@ API:

String expression = "/Employees/Employee";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++) {
    Node employeeNode = nodeList.item(i);
    String emplId = employeeNode.getAttributes().getNamedItem("emplid").getNodeValue();
}

http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html#getAttributes()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章