我收到以下xml响应,我需要解析,以便我得到的是URL128 xml元素值的集合。有关在Java中实现这一目标的最有效方法的任何想法吗?
<?xml version="1.0" encoding="utf-8"?>
<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>
<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>
答案 0 :(得分:4)
Java XPath API易于使用:
String xmlData = "<test><one><URL128 myAttribute='value' /></one></test>";
InputSource source = new InputSource(new StringReader(xmlData)); //or use your own input source
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList list = (NodeList)xPath.evaluate("//URL128", source, XPathConstants.NODESET);
List<Element> elements = new ArrayList<Element>(list.getLength());
for (int i = 0; i < list.getLength(); i++)
{
elements.add((Element)list.item(i));
}
答案 1 :(得分:2)
使用SAX并实施startElement
方法,以便在元素名称为“URL128”的情况下,提取三个属性Scope
,Type
和{{1将它们存储在自定义对象中,并将此对象添加到Value
。
既简单又快捷。