How to XmlObject.selectPath() by *default* namespace?

霸气de小男生 提交于 2019-12-22 10:47:38

问题


I found this method of querying an XmlObject to return an element containing a particular namespace:

   XmlObject xobj = XmlObject.Factory.parse(
            "<a xmlns='testA'>\n" +
            "  <B:b xmlns:B='testB'>\n" +
            "    <B:x>12345</B:x>\n" +
            "  </B:b>\n" +
            "</a>");

    // Use xpath with namespace delcaration to find <B:b> element.
    XmlObject bobj = xobj.selectPath(
            "declare namespace B='testB'" +
            ".//B:b")[0];

This is pretty straightforward and can be used for other named namespaces, but how do I do the same for a default namespace? i.e. xmlns= like this:

   XmlObject xobj = XmlObject.Factory.parse(
            "<a xmlns='testA'>\n" +
            "  <b xmlns='testB'>\n" +
            "    <x>12345</B:x>\n" +
            "  </b>\n" +
            "</a>");

The xmlbeans documentation only refers to named namespaces... Is there a way to accomplish what I am looking for?


回答1:


I found the XMLBeans default namespace answer at Applying XPath to an XML with or without namespace.

Applying it to your example:

String nsDeclaration = "declare default element namespace 'testB';";
XmlObject bobj = xobj.selectPath(nsDeclaration + ".//b")[0];



回答2:


Namespace prefixes in xml are essentially an alias for the namespace uri. In other words, the namespace prefix doesn't matter -- just the namespace URI. You can declare the namespace prefix in your xpath even though it doesn't appear in the xml document. For example, you can refer to the default namespace using the 'B' prefix in the xpath:

    // document using default namespace
    XmlObject xobj = XmlObject.Factory.parse(
            "<a xmlns='testA'>\n" +
            "  <b xmlns=''>\n" +
            "    <x>12345</x>\n" +
            "  </b>\n" +
            "</a>");

    // Use xpath with default namespace declaration to find <b> element.
    XmlObject bobj = xobj.selectPath(
            "declare namespace B=''; " +
            ".//B:b")[0];


来源:https://stackoverflow.com/questions/19792820/how-to-xmlobject-selectpath-by-default-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!