在名称空间带有XOM子元素的XML上应用xpath [英] Applying xpath on XML where namespaces are with children with XOM

查看:368
本文介绍了在名称空间带有XOM子元素的XML上应用xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XOM库来解析xml.我有以下XML

I'm using XOM library to parse xmls. I have the following XML

<ns4:parent xmlns:ns4="http://sample.xml.com/ns4">
    <ns4:child1 xmlns:ns1="http://sample.xml.com/ns1" xmlns:xsi="http://sample.xml.com/xsi">
        <ns1:child2>divaStatus</ns1:child2>
        <xsi:child>something</xsi:child>
    </ns4:child1>
</ns4:parent>

我想应用一个像ns4:parent/ns4:child1/ns1:child2这样的xpath.所以我的代码就像下面的

And I want to apply a xpath like ns4:parent/ns4:child1/ns1:child2. So my code is like below

Document doc = new Builder().build(inStream);  //inStream is containing the xml
XPathContext xc = XPathContext.makeNamespaceContext(doc.getRootElement());
doc.query("ns4:parent/ns4:child1/ns1:child2", xc);

我在这里得到XPathException.

 Exception in thread "main" nu.xom.XPathException: XPath error: XPath expression uses unbound namespace prefix ns1.

我可以理解,由于我只是通过Root Element来创建名称空间上下文,因此无法获取其子级名称空间.因此,一种变通方法可能是遍历所有子级并收集其子级名称空间并将其添加到XpathContext对象中.但是我的xml可以是10到20k行.因此,我担心遍历方法的效率如何.

I can understand that since im making the namespace context by Root Element only, its not getting the namespaces of its children. So one work around might be traversing through all the children and collecting their namespaces and add it into the XpathContext object. But my xml can be of 10 to 20k lines. So Im afraid that how efficient the traversal approach will be.

期待有更好的建议

推荐答案

这很容易(或者考虑到XPath和XML命名空间的设计,它尽可能地容易).您只需要手动将要使用的任何名称空间添加到上下文中即可.例如,在这种情况下,

This is easy (or as easy as it can be, given the design of XPath and XML Namespaces). You just need to add any namespaces you want to use to the context manually. For instance, in this case,

XPathContext xc = new XPathContext();
xc.addNamespace("ns4", "http://sample.xml.com/ns4");
xc.addNamespace("ns1", "http://sample.xml.com/ns1");
doc.query("ns4:parent/ns4:child1/ns1:child2", xc);

请注意,您不必在XPath表达式中使用与文档使用相同的前缀.

Note that you do not have to use the same prefixes in the XPath expression that the document uses.

这篇关于在名称空间带有XOM子元素的XML上应用xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆