2011-08-11 114 views
1

我想使用XPath從xml中提取「ImageUID」元素值(即{7f2535d0-9a41-4997-9694-0a4de569e6d9})和「URL128」元素值(即http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg)像下面的字符串。即使這裏只有一個,也可以有多個「圖像」元素。下面的代碼只提取了URL128的值,但我還需要獲取相應的ImageUID以及任何想法?使用XPath提取多個節點

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

檢查這個XPath 1.0出來:

"/imagesXML/Images/Image/*[self::ImageUID or self::URRL128]/@Value" 

在你輸入所示,你實際上並不需要的命名空間,我認爲。否則,您可以簡單地將它們添加或按local-name()進行選擇。

+1

感謝您的回覆empo。我沒有包含我所有的xml以使它更易於閱讀。有一部分是命名空間。 – c12