In the process of doing general XML data exchange, I prefer to pass the XML string instead of the formatted XML Document. This involves the XML string and XML document conversion problem, plainly this is a very simple problem, this article on the various XML parsers are listed below, in order to facilitate their own future review.
First, using the most primitive javax.xml.parsers, the standard JDK API
String goto 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);
XML to String
Transformerfactory tf = Transformerfactory.newinstance ();
Transformer t = Tf.newtransformer ();
T.setoutputproperty (\ "encoding\", \ "gb23121\");//solve Chinese problems, try to use GBK
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
Second, the use of dom4j after the program becomes more simple
String goto XML
String xmlstr =\ "... \";
Document document = Documenthelper.parsetext (XMLSTR);
XML to String
Document document = ...;
String text = Document.asxml ();
The XML Document here is Org.dom4j.Document
Third, the use of jdom
The processing of jdom is very similar to the first method of processing
String goto XML
String xmlstr =\ "..... \";
StringReader sr = new StringReader (XMLSTR);
InputSource is = new InputSource (SR);
Document doc = (new Saxbuilder ()). Build (IS);
XML to String
Format format = Format.getprettyformat ();
Format.setencoding (\ "gb2312\");//Set the character of the XML file as gb2312, solve the Chinese problem
Xmloutputter xmlout = new Xmloutputter (format);
Bytearrayoutputstream bo = new Bytearrayoutputstream ();
Xmlout.output (DOC,BO);
String xmlstr = bo.tostring ();
The XML Document here is Org.jdom.Document
Iv. processing in JavaScript
String goto XML
var xmlstr =\ "..... \";
var xmldoc = new ActiveXObject (\ "microsoft.xmldom\");
Xmldoc.async=false;
Xmldoc.loadxml (XMLSTR);
I can handle this xmldoc.
var name = Xmldoc.selectsinglenode (\ "/person/name\");
alert (Name.text);
XML to String
var xmldoc = ...;
var xmlstr = Xmldoc.xml
The XML document here is the JavaScript version of XMLDOM
"Reprint" XML and string convert each other