In the general XML data exchange process, I prefer to pass the XML string instead of the formatted XML document. 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"); // solves 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. 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.