使用XPath解析XML字符串数据的问题

时间:2011-08-10 20:48:02

标签: java xml xpath

我正在尝试使用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]',但它应该是我尝试提取的网址:http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:5)

如果您尝试更改此XPath评估声明该怎么办:

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

到此:

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

答案 1 :(得分:1)

注意:

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

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

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