【问题标题】:Evaluate xpath expression using local-name() function when xml has namespaces and multiple tags当 xml 具有命名空间和多个标签时,使用 local-name() 函数评估 xpath 表达式
【发布时间】:2016-04-07 20:09:16
【问题描述】:

我必须从下面的 xml 中提取文本“testpoc”。 请通过提供相关的 xpath 来帮助我。

               '<am:entry>`    `    
  `                <am:content type="application/xml">`
                    `<s:series-poc>`
                       '<s:c_series.c_id>testpoc</s:c_series.c_id>'   
                     </s:series-poc>                    
                   </am:content>
                </am:entry>

我尝试使用以下路径,但没有成功。

a)("//*[local-name()='c_series.c_id']/text()"),

b)("/entry/content/series-poc/c_series.c_id/text()"),

c)("/entry/content/series-poc//*[local-name()='c_series.c_id']/text()")

感谢您在这方面的所有支持。

【问题讨论】:

    标签: xml xpath namespaces xml-namespaces


    【解决方案1】:

    您的 XPath API 应该提供某种方式将命名空间前缀绑定到 URI,例如

    XPath.declareNamespace("am", "http://something.com/");
    XPath.declareNamespace("s", "http://something.else.com/");
    

    然后您可以选择内容为

    /am:entry/am:content/s:c_series.c_id
    

    如果您无法以这种方式绑定前缀,则依赖于 local-name() 的谓词是最后的手段。

    您使用的是什么 API?

    【讨论】:

    • 嗨,迈克尔,感谢您的快速回复。我已经发布了我的命名空间和整个 xml。我还发布了我试图制定我的 xpath 的代码,但是,在提取相应的文本时没有运气。
    【解决方案2】:

    为您提供详细信息,还请检查下面的 xml -

    使用的命名空间: xmlns:c="http://iddn.abc.com/ns/core" xmlns:f="http://iddn.abc.com/ns/fields" xmlns:a="http://iddn.abc .com/ns/assets" xmlns:s="http://iddn.abc.com/ns/search">

         <atom:entry>
            <atom:content type="application/vnd">
              <s:series-item-abc-poc>
                <s:c_series.c_id>testpoc</s:c_series.c_id>
              </s:series-item-abc-poc>
             </atom:content>
         </atom:entry>
    

    我尝试按照您的建议声明命名空间,但是,我无法获取 s:c_series.c_id 标记的值。这就是我所做的-

    xpath = XPathFactory.newInstance().newXPath();

    XPath.declareNamespace("s", "http://iddn.abc.com/ns/search");

    expr = xpath.compile("//atom:entry/atom:content/s:series-item-abc-poc/s:c_series.c_id/text()");

    如果我在这里遗漏了什么,请告诉我。

    感谢您对此的支持。

    【讨论】:

    • 注意,这个答案为使用 JAXP API 从 Java 应用程序运行 XPath 表达式的情况提供了解决方案。问题中没有任何内容表明这是 OP 正在使用的编程语言或 API。我向 OP 询问了 API 的详细信息,但他们似乎不明白这个问题。
    • 请忽略之前的评论:我误读了您的“答案”,没有意识到它实际上是对问题的补充。这个“答案”应该是对原始问题的编辑。它表明您使用的 API 是 Java JAXP API。您正在使用正确的方法,但当然您需要声明“atom”命名空间以及“s”命名空间。如果您解决问题的尝试失败,请更具体地说明失败的具体原因。
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多