0

XML

<?xml version="1.0"?>
<Employees>
    <Employee emplid="1111" type="admin">
        <firstname>John</firstname>
        <lastname>Watson</lastname>
        <age>30</age>
        <email>johnwatson@sh.com</email>
    </Employee>
    <Employee emplid="2222" type="admin">
        <firstname>Sherlock</firstname>
        <lastname>Homes</lastname>
        <age>32</age>
        <email>sherlock@sh.com</email>
    </Employee>
    <Employee emplid="3333" type="user">
        <firstname>Jim</firstname>
        <lastname>Moriarty</lastname>
        <age>52</age>
        <email>jim@sh.com</email>
    </Employee>
    <Employee emplid="4444" type="user">
        <firstname>Mycroft</firstname>
        <lastname>Holmes</lastname>
        <age>41</age>
        <email>mycroft@sh.com</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。非常感谢任何建议或参考链接。

4

3 回答 3

1

您的 XPath 应该是 /Employees/Employee/@emplid 要学习 XPath,请遵循本教程

http://www.w3schools.com/XPath/

于 2014-03-11T09:25:31.727 回答
1

看看@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()

于 2014-03-11T09:26:29.710 回答
1

您需要创建三个单独的 xpath 表达式。

  • 对于 emplide 来说,这将是/Employees/Employee[@emplid]
  • 对于类型,它将是/Employees/Employee[@type]

Ans第三个是你用过的那个..

如果您想了解更多关于 xpath 的信息,这里有一个很好的链接。

于 2014-03-11T09:28:32.457 回答