获取叶节点 - Java 中的 XML 解析



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

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

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

使用此 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

阅读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

}

试试这段代码...我将您的 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

最新更新