xml| Conversion | String in doing general XML data interchange, I am more than happy to pass XML strings instead of formatted XML Document. This involves the conversion of XML strings and XML document, which is a very simple problem, this article lists the various XML parsers, respectively, to facilitate their future inspection.
First, the use of the most original javax.xml.parsers, the standard JDK API
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);
XML Spin string
Transformerfactory tf = Transformerfactory.newinstance ();
Transformer t = Tf.newtransformer ();
T.setoutputproperty (\ "encoding\", \ "gb23121\")/solve Chinese problems, try to use GBK not
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 simpler
String to XML
String xmlstr = \ "... \";
Document document = Documenthelper.parsetext (XMLSTR);
XML Spin string
Document document = ...;
String text = Document.asxml ();
The XML Document here is Org.dom4j.Document
Iii. Use of Jdom
The jdom approach is very similar to the first method processing
String to XML
String xmlstr = \ "... \";
StringReader sr = new StringReader (XMLSTR);
InputSource is = new InputSource (SR);
Document doc = (new Saxbuilder ()). Build (IS);
XML Spin string
Format format = Format.getprettyformat ();
Format.setencoding (\ "gb2312\");//Set the character of the XML file to 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
Four, the processing in the JavaScript
String to XML
var xmlstr = \ "... \";
var xmldoc = new ActiveXObject (\ "microsoft.xmldom\");
Xmldoc.async=false;
Xmldoc.loadxml (XMLSTR);
We can handle this xmldoc.
var name = Xmldoc.selectsinglenode (\ "/person/name\");
alert (Name.text);
XML Spin string
var xmldoc = ...;
var xmlstr = Xmldoc.xml
The XML document here is the JavaScript version of XMLDOM