Consider the following stanza:
<message>
<body>bar</body>
<x xmlns="myns">
<content>foo</content>
</x>
</message>
which is then passed to a function called getFoo(message), that will extract the value of <content>. I was having trouble getting that value using message.stanza.x.content, so I found an alternative way, by parsing the xml stanza through xml string.
What we need to do:
//declare a namespace var to make things easier...to read
ns = "myns";
//get the <x> node only
var x = message.stanza.ns::x;
//extracting the position value
var foovalue = loadXMLString(x);
//function to parse through XML String .. from w3schools.com
function loadXMLString(XMLtext)
{
//alert(XMLtext);
var parser=new DOMParser();
var doc=parser.parseFromString(XMLtext,"text/xml");
// documentElement always represents the root node
var x=doc.documentElement;
return x.childNodes[1].childNodes[0].nodeValue; //the <content> value..... Why so many childNodes? see below.
}
Why so many childNodes?
Even though the xml string we extracted (<x> node only) will be something like this:
<x xmlns="myns">
<content>foo</content>
</x>
In plain eyes, it looks like <x> have only 1 child node (content), but instead it has 3 nodes actually. The real stanza would be something like this:
<x xmlns="myns">
--- invisible textnode ---
<content>foo</content>
--- invisible textnode ---
</x>
you can prove this by displaying the nodeType for all the children:
x.childNodes[0].nodeType; // text
x.childNodes[1].nodeType; // element (<content>)
x.childNodes[2].nodeType; // text
ref:
http://www.w3schools.com/dom/dom_parser.asp
http://truetalkdev.blogspot.com/2007/06/sps-chat-events-stanzas.html
Friday, September 21, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment