Java 如何检索实际数据标记中的文本?
我的xml文件如下所示:Java 如何检索实际数据标记中的文本?,java,xml,xpath,nodelist,Java,Xml,Xpath,Nodelist,我的xml文件如下所示: <xml> <group id="1"> <dstport>8080</dstport> <packet id="1"> <comp type="const"> <actual-data><![CDATA[GET /]]></actual-data>
<xml>
<group id="1">
<dstport>8080</dstport>
<packet id="1">
<comp type="const">
<actual-data><![CDATA[GET /]]></actual-data>
<binary><![CDATA[47 45 54 20 2f ]]></binary>
</comp>
<comp type="var">
<actual-data><![CDATA[host-manager/html HTTP]]></actual-data>
<binary><![CDATA[68 6f 73 74 2d 6d 61 6e 61 67 65 72 2f 68 74 6d 6c 20 48 54 54 50 ]]></binary>
</comp>
</packet>
</group>
</xml>
但它给出的是空字符串。
是因为[CDATA]这件事吗。我还没弄明白那是什么。它是标记还是属性
任何人都可以通过查询来获得应得的数据。
(在本例中为“主机管理器/html HTTP”)您的xpath表达式不明确: 此代码:
InputSource inputSource = new InputSource("test.xml");
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("
/xml/group/packet/comp/actual-data/text()");
String s = expr.evaluate(inputSource);
System.out.println(s);
将显示:
GET /
这是第一个实际数据标记的内容。如果您想要第二个,您应该更具体:
XPathExpression expr = xpath.compile("
/xml/group/packet/comp[@type='var']/actual-data/text()");
有两个结果。因此,如果您希望这两个项目都返回,请执行以下操作:
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = "/xml/group/packet/comp/actual-data";
InputSource inputSource = new InputSource("test.xml");
NodeList nodes = (NodeList) xpath
.evaluate(xpathExpression, inputSource, XPathConstants.NODESET);
int j = nodes.getLength();
for (int i = 0; i < j; i++) {
System.out.println("node:" + nodes.item(i).getTextContent());
}
XPath=XPathFactory.newInstance().newXPath();
字符串xpathExpression=“/xml/group/packet/comp/actual data”;
InputSource InputSource=新的InputSource(“test.xml”);
节点列表节点=(节点列表)xpath
.evaluate(xpathExpression、inputSource、XPathConstants.NODESET);
int j=nodes.getLength();
对于(int i=0;i
另请注意,此文档中有2个匹配项(“GET/”是第一个匹配项)。这不是关于XPath,而是关于XPath结果数据类型的使用。重新标记。
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = "/xml/group/packet/comp/actual-data";
InputSource inputSource = new InputSource("test.xml");
NodeList nodes = (NodeList) xpath
.evaluate(xpathExpression, inputSource, XPathConstants.NODESET);
int j = nodes.getLength();
for (int i = 0; i < j; i++) {
System.out.println("node:" + nodes.item(i).getTextContent());
}