【发布时间】:2014-05-06 04:41:13
【问题描述】:
我正在使用 XPath 从 xml 中获取节点的名称和值,但我正在尝试的代码没有得到节点名称... 这是我正在解析的xml
<?xml version="1.0" encoding="UTF-8"?>
<reg>
<user>
<Name>adil</Name>
<Email>adil@gmail.com</Email>
<Picture>/storage/sdcard0/DCIM/browser-photos/1352975129941.jpg</Picture>
<LastEdited>26 Mar 2014 11:49:39</LastEdited>
</user>
<user>
<Name>zeeshan</Name>
<Email>zajmal@gmail.con</Email>
<Picture>/storage/sdcard0/DCIM/browser-photos/1352975129941.jpg</Picture>
<LastEdited>26 Mar 2014 11:49:39</LastEdited>
</user>
</reg>
这是我正在尝试的代码
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Email[text()='"adil@gmail.com"']";
System.out.println(expression);
Node node = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);
if(null != node) {
Node pNode = node.getParentNode();
nodeList = pNode.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE)
{
System.out.println(nod.getFirstChild().getNodeName().toString() + " : " + nod.getFirstChild().getNodeValue());
}
system.out.println() 的输出是
#text : adil
#text : adil@gmail.com
#text : /storage/emulated/0/DCIM/browser-photos/1352975129941.jpg
#text : 26 Mar 2014 11:49:39
我无法选择我错的地方......
【问题讨论】:
-
您是否也尝试打印父节点名称? AFAIK 两个标签之间的文本也是一个节点,即
<Name>adil</Name>将是两个节点:Name和text(一个未命名的文本节点)。我的意思是:而不是nod.getFirstChild().getNodeName()尝试nod.getNodeName()。 -
@Thomas:谢谢它的工作
标签: java android xpath xml-parsing