是否有一个 XPath 表达式可用于在 CDATA 部分中导航 XML? [英] Is there a single XPath expression I can use to navigate XML in a CDATA section?

查看:29
本文介绍了是否有一个 XPath 表达式可用于在 CDATA 部分中导航 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用 XPath 从以下 XML 文档中的 XML 片段中获取 exceptionID 和 instrumentID 值(是的,在 CDATA 中包含 XML 有点奇怪,但这就是我从第三方服务)

I'm trying to figure out how to use XPath to get the exceptionID and instrumentID values out of the XML snippet in the following XML document (yes having XML in the CDATA is a little odd, but that's what I get from the 3rd party service)

<?xml version="1.0"?>
  <exception>
    <info>
      <![CDATA[
        <info>
          <exceptionID>1</exceptionID>
          <instrumentID>1</instrumentID>
        </info>
      ]]>
    </info>
</exception>

是否可以在一个 XPath 语句中获取值?

Is it possible to get the values in one XPath statement?

我在 Java(带有 Xalan 2.7.1 和 Xerces 2.9.1 的 JDK 1.5)中使用 javax.xml.xpath.XPath,例如

I'm using javax.xml.xpath.XPath inside Java (JDK 1.5 with Xalan 2.7.1 and Xerces 2.9.1), e.g.

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

Long exceptionId  = new Long(((Double)xpath.evaluate(this.exceptionIdXPath, 
                               document, XPathConstants.NUMBER)).longValue());

我不知道如何设置 this.exceptionIdXPath 变量,例如我知道:

It's the this.exceptionIdXPath variable that I'm not sure how to set, I know for example that:

/exception/info/text()/info/exceptionID 不起作用(text() 返回 CDATA 内的数据,但不知道它是 XML)

/exception/info/text()/info/exceptionID won't work (text() returns the data inside the CDATA but with no 'knowledge' that it is XML)

推荐答案

是的,你可以做到.但是 CDATA 部分中的任何内容都是字符串,不会成为 DOM 的一部分.因此,您必须使用 XPath 的字符串操作函数.

Yes, you can do it. But anything inside the CDATA section is a string and won't be part of the DOM. Therefore, you have to use XPath's string manipulation functions.

在 XPath 中,您可以使用 substring-before 和 substring-after.像这样的事情可能会奏效:

In XPath you can use substring-before and substring-after. Something like this may work:

substring-before(substring-after(/exception/info,"<exceptionID>"), "</exceptionID>")

这篇关于是否有一个 XPath 表达式可用于在 CDATA 部分中导航 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆