2013-04-29 58 views
0

我从web服务作为String它看起来像这样的响应。XML字符串到对象阵列

<?xml version="1.0" ?> 
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"> 
    <S:Body><ns2:getTitlesResponse xmlns:ns2="http://localhost:8080/wsGrabber/GrabberService"> 
     <return> 
      <titles>sampleTitle</titles> 
      <urls>http://sample.com</urls> 
     </return> 
    </ns2:getTitlesResponse> 
    </S:Body> 
</S:Envelope> 

如何获取数组标题和URL?

+1

与SOAP解析器像Axis2中使用它 - 有一个谷歌针对的看些例子。 – david99world 2013-04-29 08:08:13

回答

2

XPath是什么,如果你想搜索在XML文件东西,你应该使用。

try { 
     DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory 
       .newInstance(); 
     documentBuilderFactory.setNamespaceAware(true); 
     DocumentBuilder builder = documentBuilderFactory 
       .newDocumentBuilder(); 
     Document doc = builder.parse("path/to/xml/MyXML.xml"); 

     XPathFactory xPathFactory = XPathFactory.newInstance(); 
     XPath xpath = xPathFactory.newXPath(); 

     XPathExpression expression = xpath 
       .compile("//titles"); 

     NodeList nodes = (NodeList) expression.evaluate(doc, 
       XPathConstants.NODESET); 

     for (int i = 0; i < nodes.getLength(); i++) { 
      //System.out.println(nodes.item(i).getNodeName()); 
      System.out.println(nodes.item(i).getTextContent()); 
     } 
    } catch (Exception exception) { 
     exception.printStackTrace(); 
    } 

编辑

String input = "XMLAsString"; 
InputStream is= new ByteArrayInputStream(input.getBytes()); 
Document doc = builder.parse(is); 
+0

感谢您的快速回复。但是你的例子需要一个xml文件。我只有一个字符串,我不想将它保存为xml文件。 – haisi 2013-04-29 08:41:23

+0

@haisi见编辑。 – Eugene 2013-04-29 08:47:46