I am parsing this XML document:
<?xml version='1.0' encoding='UTF-8'?>
<team xmlns='http://www.example.com/default' xmlns:ns1='http://www.example.com/ns1'>
<ns1:coach ns1:coachAttr="ABC"/>
<player playerAttr="XYZ"/>
</team>
I would expect player
and playAttr
to be in the http://www.example.com/default
namespace, while coach
and coachAttr
would be in the http://www.example.com/ns1
namespace.
Turns out playerAttr
has no namespace at all. Here is the code:
String xml="...";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml)));
Element team = doc.getDocumentElement();
Element player = (Element) team.getChildNodes().item(...);
Element coach = (Element) team.getChildNodes().item(...);
Attr playerAttr = (Attr) player.getAttributes().item(...);
Attr coachAttr = (Attr) coach.getAttributes().item(...);
System.out.println("coach: Name=" + coach.getLocalName() + " NS=" + coach.getNamespaceURI());
System.out.println("coachAttr: Name=" + coachAttr.getLocalName() + " NS=" + coachAttr.getNamespaceURI());
System.out.println("player: Name=" + player.getLocalName() + " NS=" + player.getNamespaceURI());
System.out.println("playerAttr: Name=" + playerAttr.getLocalName() + " NS=" + playerAttr.getNamespaceURI());
This prints out 4 lines. The first 3 make sense to me. I do not understand the last line, where NS is null.
coach: Name=coach NS=http://www.example.com/ns1
coachAttr: Name=coachAttr NS=http://www.example.com/ns1
player: Name=player NS=http://www.example.com/default
playerAttr: Name=playerAttr NS=null
Why is playerAttr
treated differently? Is this in some kind of spec? What does it even mean that an items has no namespace?