Once again I’m doing a lot of JavaScript, but with XML. I have also been tasked with getting this JS to work in FireFox and IE.
Some of the thing I’m having to do are the following:
Load XML
Create new Node/Elements
Edit Attribute
Find Node/Element (based on XPath)
//This works with IE and FireFox
function LoadXml(xml) {
var xmlDoc = null;
if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
} else if (document.implementation && document.implementation.createDocument) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
}
return xmlDoc;
}
var xmlDoc = null;
if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xml);
} else if (document.implementation && document.implementation.createDocument) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
}
return xmlDoc;
}
function FindNodeOnElementAndAttribute(xmlDoc, elementName, attributeName, attributeValue) {
var node
var xPath = "//" + elementName + "[@" + attributeName + "=’" + attributeValue + "’]";
if (window.ActiveXObject) {
node = xmlDoc.selectSingleNode(xPath);
} else if (XPathEvaluator) {
var xpe = new XPathEvaluator();
var nsResolver = xpe.createNSResolver(xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
var results = xpe.evaluate(xPath, xmlDoc, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
node = results.singleNodeValue;
}
return node;
}
var node
var xPath = "//" + elementName + "[@" + attributeName + "=’" + attributeValue + "’]";
if (window.ActiveXObject) {
node = xmlDoc.selectSingleNode(xPath);
} else if (XPathEvaluator) {
var xpe = new XPathEvaluator();
var nsResolver = xpe.createNSResolver(xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
var results = xpe.evaluate(xPath, xmlDoc, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
node = results.singleNodeValue;
}
return node;
}
Resources:
XML DOM Create Nodes (W3schools.com)
XPath Axes(W3schools.com)
XML DOM Examples
Parsing the XML DOM
XML DOM Load Function
DevGuru – XMLDom Documentation
Using JavaScript to retrive XML in IE and FireFox
FireFox – Converting XMLObject to String
selectSingleNode and FireFox
Parsing XML in JavaScript
How do I load an XML formatted string into the DOM?
Problem retrieving string value of XML document in Firefox