【问题标题】:Problem using XPath to Parse XML String Data使用 XPath 解析 XML 字符串数据的问题
【发布时间】:2011-08-10 20:48:01
【问题描述】:

我正在尝试使用 XPath 解析 XML 字符串,但我只得到空值。有谁知道我在下面显示的代码中可能出错的地方?

public static void main(String[] args) {
    String content = "<imagesXML><Images><Image><ImageUID Scope='Public' Type='Guid' Value='{7f2535d0-9a41-4997-9694-0a4de569e6d9}'/><CorbisID Scope='Public' Type='String' Value='42-15534232'/><Title Scope='Public' Type='String' Value='Animal'/><CreditLine Scope='Public' Type='String' Value='© Robert Llewellyn/Corbis'/><IsRoyaltyFree Scope='Public' Type='Boolean' Value='False'/><AspectRatio Scope='Public' Type='String' Value='1.500000'/><URL128 Scope='Public' Type='String' Value='http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg'/></Image></Images></imagesXML>";
    InputSource source = new InputSource(new StringReader(content));
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList list = null;
    try {
        list = (NodeList) xPath.evaluate("//URL128[@Value]", source,
                XPathConstants.NODESET);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    for (int i = 0; i < list.getLength(); i++) {
        System.out.println(list.item(i));
    }
}

System.out 的输出是 'value=[URL128: null]',但它应该是我要提取的 URL:http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg

任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: java xml xpath


    【解决方案1】:

    如果您尝试从此更改您的 XPath 评估语句会怎样:

    list = (NodeList)xPath.evaluate("//URL128[@Value]", 
        source, XPathConstants.NODESET);
    

    到这里:

    list = (NodeList) xPath.evaluate("//URL128/@Value", 
        source, XPathConstants.NODESET);
    

    【讨论】:

    • 谢谢,成功了。我得到 Value="cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/…" 有没有办法使用 XPath 评估删除 Value= 部分?
    • 啊,明白了 System.out.println(list.item(i).getTextContent());
    • @c12:当然,如果您知道它不会在字符串的主体中表示,您可以使用String#replaceString#replaceAll 来做到这一点。 -- 没关系,你的方式更好!
    【解决方案2】:

    注意:

    • 表达式//URL128[@Value] 返回具有Value 属性的所有URL123 元素的列表
    • 表达式//URL128/@Value 返回源中每个URL128 元素的Value 属性列表

    这些列表都不包含字符串;它们包含 DOM 类型。您的源代码中只有一个 URL128 元素,但您要求的是 NodeList。您可以使用以下方法进行简化:

    String url = xPath.evaluate("//URL128/@Value", source);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多