获取叶节点 - 使用Java进行XML解析

时间:2013-12-26 10:48:01

标签: java xml

是否可以解析XML并获取所有叶节点?

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

我的输出应该是 名称 年龄 分支

3 个答案:

答案 0 :(得分:7)

使用此XPath表达式查找没有其他元素作为子元素的alle元素://*[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();
}

结果是

name
age
branch

答案 1 :(得分:0)

阅读xml非常简单。

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


}

答案 2 :(得分:0)

尝试此代码...我将您的xml代码保存在桌面文件夹中的e.xml中,并从您的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();
    }
  }

<强>输出

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