我尝试使用xpath获取XML块(不仅仅是元素值)。进入这样的几篇文章,http://www.journaldev.com/1194/java-xpath-tutorial-with-examples,我能够对所提到的查询得到很好的回答。但是,如何将XML块作为 / Employees 等xpath的响应?
即,获得回复,
<Employee id="1">
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee id="2">
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
<Employee id="3">
<age>40</age>
<name>Tom</name>
<gender>Male</gender>
<role>Manager</role>
</Employee>
<Employee id="4">
<age>25</age>
<name>Meghna</name>
<gender>Female</gender>
<role>Manager</role>
</Employee>
而不是,
29
Pankaj
Male
Java Developer
35
Lisa
Female
CEO
40
Tom
Male
Manager
25
Meghna
Female
Manager
代码:
package com.eugthom.xmlBlock;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XpathEvaluate {
/**
* @param args
*/
public static void main(String[] args) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse("C:\\Users\\thoeu01\\Desktop\\a.xml");
// Create XPathFactory object
XPathFactory xpathFactory = XPathFactory.newInstance();
// Create XPath object
XPath xpath = xpathFactory.newXPath();
String nodeName = getEntireNode(doc, xpath);
System.out.println("Node is: " + nodeName);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
private static String getEntireNode(Document doc, XPath xpath) {
String name = null;
try {
XPathExpression expr = xpath.compile("/Employees");
// name = (String) expr.evaluate(doc, XPathConstants.STRING).toString();
name = expr.evaluate(doc);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return name;
}
}