Java – parsing XML from httppost response
•
Java
During HTTP post, I store the response as a string response
HttpResponse httpresponse = httpclient.execute(httppost); httpentity resEntity = httpresponse.getEntity(); response = EntityUtils.toString(resEntity);
If I print the response, it looks like:
<?xml version="1.0" encoding="UTF-8"?> <response status="ok"> <sessionID>lo8mdn7bientr71b5kn1kote90</sessionID> </response>
I want to store the sessionid as a string I tried
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml));
And various methods like this, but it won't let me run the code because documentbuildfactory and inputsource are invalid
What should I do to extract a specific string from this XML?
Solution
It's just a quick and dirty test It works for me
import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Test { public static void main(String[] args) { String xml= "<?xml version=\"1.0\" encoding=\"UTF-8\"?><response status=\"ok\"><sessionID>lo8mdn7bientr71b5kn1kote90</sessionID></response>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; InputSource is; try { builder = factory.newDocumentBuilder(); is = new InputSource(new StringReader(xml)); Document doc = builder.parse(is); NodeList list = doc.getElementsByTagName("sessionID"); System.out.println(list.item(0).getTextContent()); } catch (ParserConfigurationException e) { } catch (SAXException e) { } catch (IOException e) { } } }
Output: lo8mdn7bientr71b5kn1kote90
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码