> During Normal XML data exchange, I prefer to pass XML strings instead of formatted XML documents. This involves the conversion of XML strings and Xml documents. To put it bluntly, this is a very simple problem. This article lists the various XML Parser as follows to facilitate future reference.
1. Use the original javax. xml. parsers, standard jdk api
// Convert string to XML
String xmlStr = \"......\";
StringReader sr = new StringReader (xmlStr );
InputSource is = new InputSource (sr );
DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance ();
DocumentBuilder builder = factory. newDocumentBuilder ();
Document doc = builder. parse (is );
// Convert XML to string
TransformerFactory tf = TransformerFactory. newInstance ();
Transformer t = tf. newTransformer ();
T. setOutputProperty (\ "encoding \", \ "GB23121 \"); // solve Chinese problems. If you have tried GBK, it will not work.
ByteArrayOutputStream bos = new ByteArrayOutputStream ();
T. transform (new DOMSource (doc), new StreamResult (bos ));
String xmlStr = bos. toString ();
The xml document here is org. w3c. dom. Document
2. The program becomes simpler after dom4j is used
// Convert string to XML
String xmlStr = \"......\";
Document document = incluenthelper. parseText (xmlStr );
// Convert XML to string
Document document = ...;
String text = document. asXML ();
Here the xml document is org. dom4j. Document
3. Use JDOM
The JDOM processing method is very similar to the first method.
// Convert string to XML
String xmlStr = \".....\";
StringReader sr = new StringReader (xmlStr );
InputSource is = new InputSource (sr );
Document doc = (new SAXBuilder (). build (is );
// Convert XML to string
Format format = Format. getPrettyFormat ();
Format. setEncoding (\ "gb2312 \"); // set the character of the xml file to gb2312 to solve the Chinese problem.
XMLOutputter xmlout = new XMLOutputter (format );
ByteArrayOutputStream bo = new ByteArrayOutputStream ();
Xmlout. output (doc, bo );
String xmlStr = bo. toString ();
Here the xml document is org. jdom. Document
Iv. Processing in JAVASCRIPT
// Convert string to XML
Var xmlStr = \".....\";
Var xmlDoc = new ActiveXObject (\ "Microsoft. XMLDOM \");
XmlDoc. async = false;
XmlDoc. loadXML (xmlStr );
// You can process the xmlDoc.
Var name = xmlDoc. selectSingleNode (\ "/person/name \");
Alert (name. text );
// Convert XML to string
Var xmlDoc = ......;
Var xmlStr = xmlDoc. xml
Here, the xml document is the xml dom of the javascript version.