【问题标题】:How to XmlObject.selectPath() by *default* namespace?如何通过 *default* 命名空间使用 XmlObject.selectPath()?
【发布时间】:2013-11-16 13:16:30
【问题描述】:

我发现了这种查询 XmlObject 以返回包含特定命名空间的元素的方法:

   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];

这很简单,可以用于其他命名的命名空间,但我如何为 default 命名空间做同样的事情?即xmlns= 像这样:

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

xmlbeans documentation 仅指 named 命名空间...有没有办法完成我正在寻找的东西?

【问题讨论】:

    标签: java xml xpath namespaces xmlbeans


    【解决方案1】:

    我在Applying XPath to an XML with or without namespace 找到了 XMLBeans 默认命名空间答案。

    将其应用于您的示例:

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

    【讨论】:

      【解决方案2】:

      xml 中的命名空间前缀本质上是命名空间 uri 的别名。换句话说,命名空间前缀无关紧要——只是命名空间 URI。您可以在 xpath 中声明名称空间前缀,即使它没有出现在 xml 文档中。例如,您可以使用 xpath 中的“B”前缀来引用默认命名空间:

          // 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];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-23
        • 1970-01-01
        • 2012-12-15
        • 2016-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多