使用javax.XML.xpath时使用标记查询XML Bloxk
我正在尝试使用xpath获取XML块(不仅仅是元素值)。遇到了几篇这样的文章,我能够对上面提到的问题得到很好的回答。但是,如何获取XML块作为xpath(如/Employees)的响应 i、 例如,得到回应使用javax.XML.xpath时使用标记查询XML Bloxk,java,xml,xpath,Java,Xml,Xpath,我正在尝试使用xpath获取XML块(不仅仅是元素值)。遇到了几篇这样的文章,我能够对上面提到的问题得到很好的回答。但是,如何获取XML块作为xpath(如/Employees)的响应 i、 例如,得到回应 <Employee id="1"> <age>29</age> <name>Pankaj</name> <gender>Male</gender> <role>Ja
<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>
代码:
你能分享你目前拥有的不适用于你的代码吗?@ug_u它基本上与链接中提到的相同,只是有一些小的调整。在问题中添加了代码。您需要将返回的DOM节点序列化为XML标记,使用Java,您可以使用DOM级别3加载和保存或JAXP默认转换器。
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;
}
}