0

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>

そして、のようなxp​​athを適用したい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 行になる可能性があります。したがって、トラバーサルアプローチがどれほど効率的であるかが心配です。

より良い提案をお待ちしております

4

2 に答える 2

0

おそらく、各要素名に関連付けられている名前空間を知っているでしょう。したがって、次のように書くことができます。

String xpath = "*[local-name()='parent' and namespace-uri()='http://sample.xml.com/ns4']"+
  "*[local-name()='child1' and namespace-uri()='http://sample.xml.com/ns2']"+
  "*[local-name()='child2' and namespace-uri()='http://sample.xml.com/ns1']";

プレフィックス付きのバージョンと同じくらい効率的であると期待しています。

于 2013-04-02T23:03:50.590 に答える