我想使用XPath从xml字符串中提取“ImageUID”元素值(即{7f2535d0-9a41-4997-9694-0a4de569e6d9})和“URL128”元素值(即http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg)如下。可以有多个“图像”元素,即使这里只有一个。下面的代码只提取了URL128的值,但是我还需要得到相应的ImageUID,任何想法?
String unescaped="<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(unescaped));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList list = null;
try
{
SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
nsCtx.bindNamespaceUri("ns", "http://c1.net.corbis.com/");
xPath.setNamespaceContext(nsCtx);
list = (NodeList) xPath.evaluate("//ns:URL128/@Value", source, XPathConstants.NODESET);
} catch (Exception ex)
{
log.error(ex.getMessage());
}
List<String> imageURLs = new ArrayList<String>();
for (int i = 0; i < list.getLength(); i++)
{
imageURLs.add(list.item(i).getTextContent());
}
答案 0 :(得分:0)
检查此XPath 1.0:
"/imagesXML/Images/Image/*[self::ImageUID or self::URRL128]/@Value"
如您的输入所示,我认为您实际上并不需要名称空间。否则,您只需添加它们或按local-name()
选择。