2013-04-29 56 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