I am coding an Android client that talks to some web services via XML packets. A typical packet looks like this..
<Packet service="login">
<username></username>
<password></password>
</Packet>
I have about 20 of these packets and would like to store them in my resources maybe in res/xml or res/raw
I want to store these 'empty' packets and load them using XML DOM and then fill in the content between the tags or attributes but am un开发者_Python百科sure how to do this.
Once the DOM packet has been filled in I want to get that back as a String so that I can send the packet to the server.
So to summarize my questions are..
(1) How do I load an XML resource using DOM?
(2) How do I convert the DOM object to a String?
You can use the javax.xml.parsers.*
, org.xml.sax.*
, org.w3c.dom.*
, org.xmlpull.v1.*
packages for full XML support on Android. Here's a tutorial: http://www.ibm.com/developerworks/opensource/library/x-android/index.html
Conversion from xml to DOM is done by a XML Parser, common helper libraries are jdom or dom4j. You feed a stream to the parser and the result is (if the xml is OK) a DOM document.
The other way round is done with a XMLOutputter. That's basically a writer which takes a DOM document (or a node) and writes xml to a stream. jdom and dom4j both contain such a writer.
Use ByteArrayInputStream
and ByteArrayOutputStream
to convert between streams and String.
精彩评论