2014-06-26 196 views
0

我得到一個這樣的XML肥皂XML解析Android中

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> 
<soap:Body> 
<ns2:authenticateResponse xmlns:ns2="http://auth.mobility.kra.kuali.polus.com/"  xmlns:ns3="http://rice.kuali.org/kim/v2_0"> 
<Principal> 
<ns3:principalId>10000000049</ns3:principalId> 
<ns3:principalName>shields</ns3:principalName> 
<ns3:entityId>10048</ns3:entityId> 
<ns3:active>true</ns3:active> 
<ns3:versionNumber>1</ns3:versionNumber> 
<ns3:objectId>F07352DB67502CF0E040007F0100035A</ns3:objectId> 
</Principal> 
</ns2:authenticateResponse> 
</soap:Body> 
</soap:Envelope> 

如何分析這種XML的機器人。

我試過這樣,但不工作

XMLParser parser = new XMLParser(); 
    Document doc = parser.getDomElement(xml); // getting DOM element 

    NodeList nl = doc.getElementsByTagName("soap:Body"); 

    // looping through all item nodes <item> 
    for (int i = 0; i < nl.getLength(); i++) 
    { 

    } 
+0

你爲什麼不使用KSOAP庫爲這種目的的? https://code.google.com/p/ksoap2-android/ – naveejr

回答

1

試試這個..

InputStream stream = new ByteArrayInputStream(xmlstring.getBytes("UTF-8")); 
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(stream); 

doc.getDocumentElement().normalize(); 

NodeList nodeList = doc.getElementsByTagName("Principal"); 

for (int i = 0; i < nodeList.getLength(); i++) { 

    Node node = nodeList.item(i);  

    Element fstElmnt = (Element) node; 
    NodeList nameList = fstElmnt.getElementsByTagName("ns3:principalId"); 
    Element nameElement = (Element) nameList.item(0); 
    nameList = nameElement.getChildNodes(); 

    System.out.println("ns3:principalId : "+(((Node) nameList.item(0)).getNodeValue())); 
} 
+0

我有一個字符串,有這個Xml我沒有網址。 – Anirban

+0

@bumba看我的編輯。 – Hariharan