我是 XPATH 的新手,并且遇到以下问题:
我有以下代码片段,但似乎无法按我的预期工作:
String XML = cdataContent;
// Crea un nuovo documento XML a partire dal contenuto della
// precedente sezione CDATA:
documentXML = builder.build(new StringReader(XML));
System.out.println(documentXML.toString());
System.out.println("CDATA Content in XML document:");
org.jdom.output.XMLOutputter xmlOutputterCDATAContent = new org.jdom.output.XMLOutputter(
org.jdom.output.Format.getPrettyFormat());
xmlOutputter.output(documentXML, System.out);
// Crea una nuova query XPATH per selezionare il valore del tag id e lo mette dentro l'oggetto AuthResponse:
xPath = XPath.newInstance("/root/status/id");
objectElement = (Element) xPath.selectSingleNode(documentXML);
System.out.println("Y " + objectElement.getValue() + " Y");
authResponse.setStatusResponse(objectElement.getValue());
// Crea una nuova query XPATH per selezionare il valore del tag message: e lo mette dentro l'oggetto AuthResponse:
XPath xPathMessage = XPath.newInstance("/root/status/message");
Element objectElementMessage = (Element) xPath.selectSingleNode(documentXML);
System.out.println("MESSAGE: " + objectElementMessage.getValue() + " /MESSAGE");
authResponse.setStatusResponse(objectElementMessage.getValue());
}
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这是 documentXML 变量的内容:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<status>
<id>-1</id>
<message>Login o password errate</message>
</status>
</root>
我通过前面的代码行打印它:
org.jdom.output.XMLOutputter xmlOutputterCDATAContent = new org.jdom.output.XMLOutputter( org.jdom.output.Format.getPrettyFormat());
xmlOutputter.output(documentXML, System.out);
现在我必须创建 2 个 XPATH 查询:第一个必须采用 id 标记的值(在本例中为 -1> value),第二个必须采用 message 标记内的值(在本例中为字符串值 “Login o password errate”)
好的,正如您在发布的片段中看到的那样,我已经这样做了:
1) 获取 id 标签值的 XPATH 查询:
xPath = XPath.newInstance("/root/status/id");
objectElement = (Element) xPath.selectSingleNode(documentXML);
System.out.println("Y " + objectElement.getValue() + " Y");
这个查询似乎运行良好,因为在 Eclipse 控制台中打印了:
Y -1 Y
(所以我知道-1值是正确的)
2) XPATH 查询以获取消息标记值:
然后我这样做:
XPath xPathMessage = XPath.newInstance("/root/status/message");
Element objectElementMessage = (Element) xPath.selectSingleNode(documentXML);
System.out.println("MESSAGE: " + objectElementMessage.getValue() + " /MESSAGE");
现在发生了一些奇怪的事情,因为在 Eclipse 控制台中,打印以下输出:
消息:-1/消息
而不是MESSAGE:登录o密码错误/MESSAGE如我所料(因为这是消息标签内的值)
为什么?我缺少什么?我该如何解决这种情况?Tnx
安德里亚
最佳答案
XPath xPathMessage = XPath.newInstance("/root/status/message");
Element objectElementMessage = (Element) xPath.selectSingleNode(documentXML);
修改为
XPath xPathMessage = XPath.newInstance("/root/status/message");
Element objectElementMessage = (Element) xPathMessage.selectSingleNode(documentXML);
关于java - 为什么XPATH无法访问该标签的值? ( java 语),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20291135/