2011-08-10 15 views
1

我收到下面的xml響應,我需要解析以便我得到的是URL128 xml元素值的集合。關於在Java中實現這一點的最有效方法的任何想法?使用Java爲特定元素解析XML

<?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

如果多數民衆贊成所有的XML然後SAX會不錯,但我總是問別人看看常規的XmlSlurper – Shahzeb

+1

通過「高效」,你的意思是快,或你的意思是最少的努力/代碼?如果速度很快,我可能會推薦SAX或StAX解析(甚至可以自定義解析來獲得這一個元素)。如果花費最少,那麼DOM解析甚至是提供XPath評估的第三方庫。 –

+0

編碼時不費力,不會大幅犧牲性能 – c12

回答

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)); 
} 
+0

prunge!你是否在你的例子中使用了javax.xml.bind.Element?我不確定如何從Element對象集合中提取日期。我可能有錯誤的導入... – c12

+0

@ c12 org.w3c.dom.Element – prunge

2

使用SAX,並實現startElement方法,這樣,如果的元素名稱爲「URL128」,您提取的三個屬性ScopeTypeValue,它們存儲在一個自定義的對象,這個對象添加到List

它既簡單又快捷。