简体   繁体   中英

Get leaf nodes - XML parsing in Java

Is it possible to parse an XML and get all the leaf nodes ?

<root>
<emp>
<name>abc<name>
<age>12</age>
</emp>
<dept>
<branch>cse</branch>
</dept>
</root>

My output should be name age branch

Use this XPath expression to find alle elements which have no other elements as childs: //*[count(./*) = 0] .

try {
  final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("input.xml");
  final XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//*[count(./*) = 0]");
  final NodeList nodeList = (NodeList) xpath.evaluate(doc, XPathConstants.NODESET);
  for(int i = 0; i < nodeList.getLength(); i++) {
    final Element el = (Element) nodeList.item(i);
    System.out.println(el.getNodeName());
  }
} catch (Exception e) {
  e.printStackTrace();
}

Result is

name
age
branch

reading xml is quite simple.

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadAndPrintXMLFile{

public static void main (String argv []){
try {

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));

// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());


NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);

for(int s=0; s<listOfPersons.getLength() ; s++){


Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


Element firstPersonElement = (Element)firstPersonNode; 

//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);

NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());

//------- 
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);

NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());

//----
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);

NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim());

//------


}//end of if clause


}//end of for loop with s var


}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());

}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();

}catch (Throwable t) {
t.printStackTrace ();
}
//System.exit (0);

}//end of main


}

try this code... i saved your xml code in e.xml in desktop folder and get name and age and branch from your xml

public static void main(String argv[]) {

    try {

        FileInputStream file = new FileInputStream(new File("C:/Users/devteam/Desktop/e.xml"));

        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder =  builderFactory.newDocumentBuilder();

        Document xmlDocument = builder.parse(file);

        XPath xPath =  XPathFactory.newInstance().newXPath();

        System.out.println("*************************");
        String expression = "/root/emp/name";
        String exp1="/root/emp/age";
        String exp2="/root/dept/branch";
        System.out.println(expression);
        String name = xPath.compile(expression).evaluate(xmlDocument);
        System.out.println(exp1);
        System.out.println(name);
        System.out.println(exp1);
        String age = xPath.compile(exp1).evaluate(xmlDocument);
        System.out.println(age);
        String branch = xPath.compile(exp2).evaluate(xmlDocument);
        System.out.println(branch);
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

output :

*************************
/root/emp/name
/root/emp/age
abc
/root/emp/age
12
cse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM