Search code examples
xmlxml-namespacesw3c

W3C xml get element with namespace and without namespace


I have a XML like below,

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
 <Entities xmlns="sample">
  <Entity>
    sample Value
   </Entity>
   <ns1:Entity xmlns:ns1="sample">
     sample Value
   </ns1:Entity>
 </Entities>

When I use nodeElement.getNodeName();, I can only able to get <Entity> not <ns1:Entity>.
I verified this post and tried getLocalName() instead of getNodeName(). It is not working. Also when I tried using getElementByTagNameNS("Entity","sample"), the getLength() method returned a 0.

Updated:

As mentioned in the below answer I interchanged the parameters of getElementByTagNameNS. I see an option to use getElementByTagNameNS("*","Entity") which allows me not to hardcode the namespace in the code. Now wanted to know, is there any disadvantage of using *.


Solution

  • getElementByTagNameNS("Entity","sample") should be getElementsByTagNameNS("sample","Entity"), i.e. the namespace name comes before the local name.

    You may have made a similar mistake when trying to get nodeElement.getNodeName() but you haven't posted the relevant code.