Вопрос

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>

Code

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()); 
}

By using above code I managed to fetch John,Sherlock,Jim,Mycroft. How do I do if i want to get emplid="1111" type="admin" John,emplid="2222" type="admin" Sherlock,emplid="3333" type="user" Jim,emplid="4444" type="user" Mycroft. Any advice or references link is highly appreciated.

Это было полезно?

Решение

Take a look @ the 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())

Другие советы

Your XPath should be /Employees/Employee/@emplid To learn XPath follow this tutorial

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

You need to create three seperate xpath expressions.

  • For emplid it would be /Employees/Employee[@emplid]
  • For type it would be /Employees/Employee[@type]

Ans the third is the one you have used..

If you want to read more about xpath, here is a good link.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top