m2j
m2j

Reputation: 1160

how to get xml namespace in javascript

my xml is

<message to="to_test" from="from_test">
    <test xmlns="google:mobile:data">
        {"message":"test_message"}
    </test>
</message>

i get the value {"message":"test_message"} by using the function getChildText("pcm"). But i tried to retrieve the namespace xmlns value.

I tried the following How to get XML namespace? , How to get specific XML namespace in XQuery in SQL Server with no luck, it shows me is not function error what i'm doing wrong?

I forgot to mention, I'm currently staring work with node.js.

update

the above xml output is xmpp stanza.

Here i'm getting the attrs using the following.

stanza.attrs.to gives me to_test.

stanza.attrs.from gives me from_test.

stanza.getChildText("test") gives me {"message":"test_message"}

I tried to get the xmlns using

    var parser = new DOMParser();
    var documents = parser.parseFromString(stanza, 'text/xml');
    var response = documents.responseXML.getElementsByTagName("test");
    var sunrise = response[0].getElementsByTagNameNS("[Namespace URI]", "test")[0].getAttribute("xmlns");
    console.log(sunrise);

here i got

[xmldom error]  element parse error: TypeError: source.indexOf is not a function @#[line:0,col:undefined]

Upvotes: 1

Views: 4914

Answers (2)

shaunc
shaunc

Reputation: 5611

I hit a similar error -- in my case it was because I had passed something besides a string to "parseFromString". Could this be the problem? It looks like "stanza" is not a string.

Upvotes: 1

Suresh Kumar
Suresh Kumar

Reputation: 11767

Using the standard browser's DOM parser, you can do the following:

var txt = "<message><test xmlns=\"google:mobile:data\"> {\"message\":\"test_message\"}</test></message>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(txt,"text/xml");
ns = xmlDoc.getElementsByTagName("test")[0].namespaceURI

I have tested with Chrome and IE and it works.

Upvotes: 3

Related Questions