What is the behavior of getAttributeNS?

bigmerf

New Member
I'm writing a little program in JavaScript in which I want to parse the following little XML snippet:\[code\]<iq xmlns="jabber:client" other="attributes"> <query xmlns="jabber:iq:roster"> <item subscription="both" jid="[email protected]"></item> </query></iq>\[/code\]Because I don't know, if the elements and attributes have namespace prefixes, I'm using the namespace-aware functions (\[code\]getElementsByTagNameNS\[/code\], \[code\]getAttributeNS\[/code\]).\[code\]var queryElement = iq.getElementsByTagNameNS('jabber:iq:roster', 'query')[0];if (queryElement) { var itemElements = queryElement.getElementsByTagNameNS('jabber:iq:roster', 'item'); for (var i = itemElements.length - 1; i >= 0; i--) { var itemElement = itemElements; var jid = itemElement.getAttributeNS('jabber:iq:roster', 'jid'); };};\[/code\]With this code I don't get the value of the attribute \[code\]jid\[/code\] (I get an empty string), but when I use \[code\]itemElement.getAttribute('jid')\[/code\] instead of \[code\]itemElement.getAttributeNS('jabber:iq:roster', 'jid')\[/code\] I'm getting the expected result.How can I write the code in a namespace-aware manner? In my understanding of XML, the namespace of the attribute \[code\]jid\[/code\] has the namespace \[code\]jabber:iq:roster\[/code\] and therefore the function \[code\]getAttributeNS\[/code\] should return the value \[code\][email protected]\[/code\].[UPDATE] The problem was (or is) my understanding of the use of namespaces together with XML attributes and is not related to the DOM API. Therefor I created an other question: XML Namespaces and Unprefixed Attributes. Also because XML namespaces and attributes unfortunately doesn't give me an answer.[UPDATE] What I did now, is to first check if there is the attribute without a namespace and then if it is there with a namespace:\[code\]var queryElement = iq.getElementsByTagNameNS('jabber:iq:roster', 'query')[0];if (queryElement) { var itemElements = queryElement.getElementsByTagNameNS('jabber:iq:roster', 'item'); for (var i = itemElements.length - 1; i >= 0; i--) { var itemElement = itemElements; var jid = itemElement.getAttribute('jid') || itemElement.getAttributeNS('jabber:iq:roster', 'jid'); };};\[/code\]
 
Back
Top