需要有关命名空间的xPath表达式的帮助
我需要一些xpath表达式的帮助。需要有关命名空间的xPath表达式的帮助
我有下面的XML文档:
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.test.com/search/local/ws/rest/v1">
<nodeA>text</nodeA>
<nodeB>
<nodeb1>
<nodeb1a>
<nodeTest>hello</nodeTest>
</nodeb1a>
</nodeb1>
</nodeB>
</Response>
我使用的温泉休息模板来检索数据。
这里是我使用XPath表达式来获取节点值:
xpathTemplate.evaluate("base:*", xmlSource, new NodeMapper() {
public Object mapNode(Node node, int i) throws DOMException {
Element response = (Element) node;
System.out.println("hi: " + response.getTextContent());
我加入的碱到我的命名空间的地图是这样的:
HashMap<String, String> nameSpaces = new HashMap<String, String>();
nameSpaces.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
nameSpaces.put("xsd", "http://www.w3.org/2001/XMLSchema");
nameSpaces.put("base", "http://schemas.test.com/search/local/ws/rest/v1");
((Jaxp13XPathTemplate) xpathTemplate).setNamespaces(nameSpaces);
使用表达式基地:*给我是响应节点,我可以使用.getChildNodes向每个子节点创建节点列表,并深入到子节点。
我想用xpath表达式直接获取hello值,但是我不能使它与除base之外的其他任何东西一起工作*。有人可以帮助我表达我的表情吗?
感谢
此XPath表达式:
/base:Response/base:nodeB/base:nodeb1/base:nodeb1a/base:nodeTest
假设base
势必http://schemas.test.com/search/local/ws/rest/v1
命名空间URI。
请尝试以下方法:
xpathTemplate.evaluate("/Response/nodeB/nodeb1/nodeb1a/nodeTest", ...
如果您需要关于XPath的更多信息,你可以试试下面的 http://www.zvon.org/xxl/XPathTutorial/General/examples.html
我的网站还提出了一个工具来测试你的XPath查询: http://ap2cu.com/tools/xpath/index.php5
感谢您的帮助。我无法让它工作。即使我尝试/回应,我也没有得到任何结果。 base:*是我可以工作的唯一表达式。我认为它与命名空间有关,但我不确定。任何其他想法? – blong824 2011-03-02 16:30:08
这是错误的。检查我的答案。 – 2011-03-02 16:31:34
hello = xpathTemplate.evaluateAsString("//*[local-name()='nodeTest']", source);
太棒了!这样可行。谢谢。快速的问题,让我更好地理解它。为什么我需要base:对于每个节点级别?我确实尝试了两种方法,没有它就无法运作。只是不确定,因为它只在主响应节点中使用。 – blong824 2011-03-02 16:37:33
@ Blong824:不客气。每个名称测试都需要'base:'前缀,因为所有这些元素都属于这样的名称空间URI。 – 2011-03-02 17:26:24