0

I never really know how to work with XML tags.How do I traverse the node and print particular node in the XML tag.Below is the XML file.

<Employees>
<Employee>
    <Gender></Gender>
    <Name>
        <Firstname></Firstname>
        <Lastname></Lastname>
    </Name>
    <Email></Email>
    <Projects>
        <Project></Project>
    </Projects>
    <PhoneNumbers>
        <Home></Home>
        <Office></Office>
    </PhoneNumbers>
</Employee>

There is no data but this is the structure.I am using the following code to parse it partially.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmlDocument = builder.parse("employees.xml");
System.out.println(xmlDocument.getDocumentElement().getNodeName());

I would like to print the gender and lastname values.How do I parse the tag which is inside the Name tag which in turn the Name is inside the Employee tag.

Regards.

user3464061
  • 1
  • 1
  • 2

2 Answers2

0

You should use XPATH. There is a good explanation in this post.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);
Community
  • 1
  • 1
SebastianH
  • 2,172
  • 1
  • 18
  • 29
0

Try this.

    String expression = "/Employees/Employee/Gender"; //read Gender value

    NodeList nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
    for (int j = 0; nList != null && j < nList.getLength(); j++) {
        Node node = nList.item(j);
        System.out.println("" + node.getFirstChild().getNodeValue());
    }

    expression = "/Employees/Employee/Name/Lastname"; //read Lastname value

    nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
    for (int j = 0; nList != null && j < nList.getLength(); j++) {
        Node node = nList.item(j);
        System.out.println("" + node.getFirstChild().getNodeValue());
    }
Arjit
  • 3,290
  • 1
  • 17
  • 18