I want to get the value out tag2 and I got this a xml:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ns1:schema xmlns:ns1='http://example.com'>" +
"<ns1:tag1>" +
" <ns1:tag2>value</ns1:tag2>" +
"</ns1:tag1>" +
"</ns1:schema>";
Then parse it to a document and want to get the elements by tagnameNS. But when I run this the nodelist is empty why?
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(new StringReader(xml)));
NodeList nl = doc.getElementsByTagNameNS("http://example.com", "tag2");
String a = nl.item(0).getNodeValue();
Still doesnt work with the URI.
getElementsByTagNameNSis returing a result. The issue is that you’re currently calling the wrong method to get the text content off the result elements. You need to callgetTextContext()and notgetNodeValue()DomDemo
Below is a complete code example.
Output
ALTERNATE APPROACH
You can also use the
javax.xml.xpathAPIs (included in Java SE 5 and above) to query a value from an XML document. These APIs offer a lot more control thangetElementsByTagNameNS.XPathDemo
Output