XOM ライブラリを使用して xml を解析しています。私は次の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>
そして、のようなxpathを適用したいns4:parent/ns4:child1/ns1:child2
。だから私のコードは以下のようなものです
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.
ルート要素のみで名前空間コンテキストを作成しているため、その子の名前空間を取得していないことがわかります。したがって、回避策の 1 つは、すべての子をトラバースし、それらの名前空間を収集してXpathContext
オブジェクトに追加することです。しかし、私の xml は 10 ~ 20,000 行になる可能性があります。したがって、トラバーサルアプローチがどれほど効率的であるかが心配です。
より良い提案をお待ちしております