Java HTML / XML How to - Select a XML "namespaced" node using org.w3c.dom.Node.getNamedItemNS(nsUri, name)








Question

We would like to know how to select a XML "namespaced" node using org.w3c.dom.Node.getNamedItemNS(nsUri, name).

Answer

import java.io.StringReader;
//  w w  w.  j  a v a2s.  c o  m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public class Main {
  public static void main(String[] args) throws Exception {
    String xml = "<xml xmlns:log='http://sample.com'><test log:writer='someWriter'/></xml>";
    StringReader xmlReader = new StringReader(xml);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(xmlReader));

    Element currentNode = (Element) doc.getElementsByTagName("test").item(0);
    String attributeValue = currentNode.getAttributes()
        .getNamedItemNS("http://sample.com", "writer").getNodeValue();
    System.out.println("Attribute value is " + attributeValue);
    xmlReader.close();
  }
}