04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 15: XML in JavaScript<br />

If none of the XML parsers is available, then the function simply throws an error indicating that it could<br />

not continue.<br />

This function can be used to parse any XML string and should always be wrapped in a try - catch<br />

statement just in case a parsing error occurs. Here’s an example:<br />

var xmldom = null;<br />

try {<br />

xmldom = parseXml(“ < root > < child/ > < /root > ”);<br />

} catch (ex){<br />

alert(ex.message);<br />

}<br />

//further processing<br />

For XML serialization, the same process can be followed to write a function that works in the four major<br />

browsers. For example:<br />

function serializeXml(xmldom){<br />

if (typeof XMLSerializer != “undefined”){<br />

return (new XMLSerializer()).serializeToString(xmldom);<br />

} else if (document.implementation.hasFeature(“LS”, “3.0”)){<br />

var implementation = document.implementation;<br />

var serializer = implementation.createLSSerializer();<br />

return serializer.writeToString(xmldom);<br />

} else if (typeof xmldom.xml != “undefined”){<br />

return xmldom.xml;<br />

}<br />

} else {<br />

throw new Error(“Could not serialize XML DOM.”);<br />

}<br />

The serializeXml() function accepts a single argument, which is the XML DOM document to<br />

serialize. As with the parseXml() function, the first step is to check for the most widely available<br />

solution, which is XMLSerializer . If this type is available, then it is used to return the XML string for<br />

the document. Otherwise, the DOM Level 3 solution is attempted with the final step being to use<br />

ActiveX. Since the ActiveX approach simply uses the xml property, the function checks for that property<br />

specifically. If each of these three attempts fails, then the method throws an error indicating that<br />

serialization could not take place. Generally, serialization attempts shouldn ’ t fail if you ’ re using the<br />

appropriate XML DOM object for the browser, so it shouldn ’ t be necessary to wrap a call to<br />

serializeXml() in a try - catch . Instead, you can simply use this:<br />

var xml = serializeXml(xmldom);<br />

Note that due to differences in serializing logic, you may not end up with exactly the same serialization<br />

results from browser to browser.<br />

529

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!