Forum Moderators: open

Message Too Old, No Replies

Cross Browser "innerXml"

         

Gibble

8:16 pm on Feb 25, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I need to get the entire contents of a node.

So, I have the value node with

 
var valueNode = xml.selectSingleNode('Value');

I can use the following to get the outerXml

var foo = valueNode.xml ¦¦ (new XMLSerializer()).serializeToString(valueNode);

But how can I get the innerXml value in each browser?

ps. I have selectSingleNode working in both with the following js


// Add selectNodes and selectSingleNode to non IE browsers
if (!window.ActiveXObject) {
Element.prototype.selectNodes = function(sXPath) {
var oEvaluator = new XPathEvaluator();
var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var aNodes = new Array();
if (oResult != null) {
var oElement = oResult.iterateNext();
while (oElement) {
aNodes.push(oElement);
oElement = oResult.iterateNext();
}
}
return aNodes;
}


Element.prototype.selectSingleNode = function(sXPath) {
var oEvaluator = new XPathEvaluator();
// FIRST_ORDERED_NODE_TYPE returns the first match to the xpath.
var oResult = oEvaluator.evaluate(sXPath, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (oResult != null) {
return oResult.singleNodeValue;
} else {
return null;
}
}
}

daveVk

10:41 pm on Feb 25, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



By concat of the outerXml ( or text of text nodes) of all child Nodes ?

Gibble

4:06 am on Feb 26, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yeah, that's what I ended up doing, writing a function to do that. Would have extended the Element.prototype, but alas, that doesn't work in IE...just the other browsers.

marquinhocb

3:46 am on May 6, 2009 (gmt 0)

10+ Year Member



There's a more optimal way than joining all the child element XML's (which could be quite costly for a large XML node):

function innerXml (node) 
{
return (node.xml ¦¦ (new XMLSerializer()).serializeToString(node) ¦¦ "").replace(
new RegExp("(^<\\w*" + node.tagName + "[^>]*>)¦(<\\w*\\/\\w*" + node.tagName + "[^>]*>$)", "gi"), "");
}

[edited by: coopster at 8:36 pm (utc) on May 6, 2009]
[edit reason] no personal urls please TOS [webmasterworld.com] [/edit]