2011-08-11 20 views
1

XPathを使用してxmlから "ImageUID"要素値(すなわち{7f2535d0-9a41-4997-9694-0a4de569e6d9})と "URL128"要素値(すなわちhttp://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg)を抽出したい以下のような文字列。ここにはただ1つありますが、複数の "画像"要素が存在する可能性があります。以下のコードは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