A method that parses an XML string into an XML DOM object.
The code is as follows |
Copy Code |
function Parsexml (XML) { var xmldom = null; if (typeof domparser!= "undefined") { XMLDOM = (new Domparser ()). parsefromstring (XML, "Text/xml"); var errors = Xmldom.getelementsbytagname ("ParserError"); if (errors.length) { throw new error ("XML Parsing error:" + errors[0].textcontent); } else if (document.implementation.hasFeature ("LS", "3.0")) { var implementation = Document.implementation; var parser = Implementaion.createlsparser (implementation. Mode_synchronous, NULL); var input = Implementation.createlsinput (); Input.stringdata = XML; XMLDOM = Parser.parse (input); else if (typeof activexobject!= "undefined") { XMLDOM = CreateDocument (); XMLDOM.loadXML (XML); if (xmldom.parseerror!= 0) { throw new error ("XML Parsing error:" + Xmldom.parseError.reason); } } else { throw new Error ("No XML parser available."); } return xmldom; } |
When parsing an XML string using this function, you should place it in the Try-catch statement in case of an error. Look at the following example:
The code is as follows |
Copy Code |
var xmldom = null; try{ XMLDOM = Parsexml (' Hello World '); catch (ex) { Console.log (Ex.message); }
|
A method of serializing an XML DOM object into an XML string.
The code is as follows |
Copy Code |
function Serializexml (XMLDOM) { if (typeof XMLSerializer!= "undefined") { Return (new XMLSerializer ()). Serializetostring (XMLDOM); else if (document.implementation.hasFeature ("LS", "3.0")) { var implementation = Document.implementation; var serializer = Implementation.createlsserializer (); Return serializer.writetostring (XMLDOM); else if (typeof xmldom.xml!= "undefined") { return xmldom.xml; } else { throw new Error ("Could not serialize XML DOM."); } } |
In general, as long as the appropriate XML DOM object is used for the browser, there is no way to serialize, and therefore there is no need to invoke Serializexml () in the Try-catch statement. As a result, just the following line of code:
code is as follows |
copy code |
& nbsp; var xml = Serializexml (XMLDOM); |