gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 02:22:42 25 4
gpt4 key购买 nike

我正在尝试使用 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.

感谢任何帮助,谢谢。

最佳答案

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

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

为此:

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

关于java - 使用 XPath 解析 XML 字符串数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7017582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com