Question

I have the following code where i'm trying to get the c:CreationDate nodes:

 value = '<?xml version="1.0" encoding="UTF-8"?><content><c:CreationDate>2010-09-04T05:04:53Z</c:CreationDate></content>';

 xml = (new DOMParser()).parseFromString(value, 'text/xml');

 console.log(xml.getElementsByTagName('c:CreationDate'));

Unfortunately it's returning an empty array, instead of an array with the node that is in the xml. I think that this is caused because of the ":" symbol.

Is there a way to escape it?

Note: Please, do not suggest usage on childNodes or things like this. This will not work for me since my xml is verify complex ( here is just a sample ) and will most likely change in the future and i can only rely in tag name.

Thanks!

Was it helpful?

Solution

The c in c:CreationDate denotes an XML namespace prefix. The namespace prefix is only a shortcut for the namespace. The namespace has to be defined somewhere in the document with an xmlns:c attribute. But in your document the namespace definition is missing.

So it should look like:

var value = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<content>' +
            '  <c:CreationDate xmlns:c="http://my.namespace">2010-09-04T05:04:53Z</c:CreationDate>' +
            '</content>';

or

var value = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<content xmlns:c="http://my.namespace">' +
            '  <c:CreationDate>2010-09-04T05:04:53Z</c:CreationDate>' +
            '</content>';

In this example the prefix c is assigned to the namespace http://my.namespace. The CreationDate tag is prefixed with c, so it belongs to the namespace http://my.namespace.

Then you can use the namespace aware getElementsByTagNameNS() function to query for the CreationDate element:

console.log(xml.getElementsByTagNameNS('http://my.namespace', 'CreationDate'));

As the first parameter you have to pass the real namespace name and not the prefix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top