我想使用XPath来解析XML字符串,但我只收到空值。有没有人有一个想法,我可能会在下面显示的代码出错?使用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的输出是“值= [URL128:空]”,但它应该是我试图提取的网址:http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg
。
任何帮助表示感谢,谢谢。
谢谢,这工作。我得到价值=“http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg” 有什么办法可以使用XPath评估去除Value =部分吗? – c12
ahhh,知道了System.out.println(list.item(i).getTextContent()); – c12
@ c12:当然,如果你知道它不会在String的主体中表示,那么你可以用'String#replace'或'String#replaceAll'来实现。 - 没关系,你的方式更好! –