开发者

Using XPath in XMLObject to query by namespace

I have a simple XML document

<abc:MyForm xmlns开发者_如何转开发:abc='http://myform.com'>
    <abc:Forms>
        <def:Form1 xmlns:def='http://decform.com'>
            ....
        </def:Form1>
        <ghi:Form2 xmlns:ghi='http://ghiform.com'>
            ....
        </ghi:Form2>
    </abc:Forms>
</abc:MyForm>

I'm using XMLObjects from Apache and when I try to do the following xpath expression it works perfectly

object.selectPath("declare namespace abc='http://myform.com' 
                   abc:Form/abc:Forms/*");

this gives me the 2 Form nodes (def and ghi). However I want to be able to query by specifying a namespace, so let's say I only want Form2. I've tried this and it fails

object.selectPath("declare namespace abc='http://myform.com' 
                   abc:Form/abc:Forms/*
                      [namespace-uri() = 'http://ghiform.com']");

The selectPath returns 0 nodes. Does anyone know what is going on?

Update:

If I do the following in 2 steps, then I can get the result that I want.

 XmlObject forms = object.selectPath("declare namespace abc='http://myform.com' 
                   abc:Form/abc:Forms")[0];
 forms.selectPath("*[namespace-uri() = 'http://ghiform.com']");

this gives me the ghi:Form node just like it should, I don't understand why it doesn't do it as a single XPath expression though. Thanks


The simple answer is that you can't. The namespace prefix is just a shorthand for the namespace URI, which is all that matters.

For a namespace-aware parser, your two tags are identical.

If you really want to differentiate using the prefix (although you really, really shouldn't be doing it), you can use a non namespace-aware parser and just treat the prefix as if it was part of the element name.

But ideally you should read a tutorial on how namespaces work and try to use them as they were designed to be used.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜