0

I know there are many questions and articles discussing this issue on the internet, but I somehow can't get this to work. I'm quite sure I'm missing something basic, but I can't find it.

The parsing itself:

var str="<article>Some article</article><other>Other stuff</other>";
var xmlDoc = null;
if (window.DOMParser) {
            var parser = new DOMParser();
            xmlDoc = parser.parseFromString(str,"text/xml");
        } 
else if (window.ActiveXObject) {
            xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(str);
        }


var node = xmlDoc.getElementsByTagName("article")[0].childNodes[0].nodeValue;
alert (node);

But it doesn't work, FF says that:

xmlDoc.getElementsByTagName("article")[0] is undefined

Also, it works if I use str like this:

var str="<article>Some article</article>";

So the question is, why doesn't it work? Parsing doesn't work right even if I append just one character to the end of str variable. Could you also point me out to some useful tutorial regarding this behaviour?

1
  • 2
    Maybe because it's not a valid XML structure...? Commented Apr 29, 2012 at 19:02

2 Answers 2

4

Your string isn't valid XML since it has multiple root nodes. Did you mean something like:

<article><name>Some article</name><other>Something else</other></article>
Sign up to request clarification or add additional context in comments.

Comments

1

try using

var str="<root><article>Some article</article><other>Other stuff</other></root>";


var node = xmlDoc.documentElement.getElementsByTagName("article")[0].childNodes[0].nodeValue;

documentElement property returns the root tag of an xml document , once you get the root tag, next you can extract elements by tag name , child nodes ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.