DOM getElementsByTagName () returns nodes with null values

I have an XML file as follows.

When I use getElementsByTagName("LEVEL2_ID") , I get a NodeList with Nodes , but these Nodes are NULL (in other words, getNodeValue() for each result node returns NULL ). Why is this? I need to get the content value of each node, in this case 2000 .

XML:

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Root> <Date>01/17/2012</Date> <LEVEL1> <LEVEL1_ID>1000</LEVEL1_ID> <LEVEL2> <LEVEL2_ID>2000</LEVEL2_ID> </LEVEL2> </LEVEL1> </Root> 

In Java printing, the value of the first node obtained using getElementsByTagName () returns NULL :

 NodeList nodes = document.getElementsByTagName("LEVEL2_ID"); System.out.println("Value of 1st node: " + nodes.item(0).getNodeValue()); 
+4
source share
2 answers

This is defined in the specification . The nodes of the nodeValue elements are null .

nodeValue type DOMString : the value of this node, depending on its type; see table above. When it is defined as null, setting it has no effect.

If you want to get the text content of each node, you need to iterate over all the text descendants of the node and combine their value.

However, the implementation of the API you are using may offer a method for directly extracting the text content of an element. For example, PHP DOMNode has the $textContent property.

If, as in your case, only the element-element is a text node, you can simply access its value:

 element.getFirstChild().getNodeValue() 
+7
source

If you have a node element and want to get its inner text, use getTextContent() as follows:

 NodeList nodes = document.getElementsByTagName("LEVEL2_ID"); System.out.println("Value of 1st node: " + nodes.item(0).getTextContent()); 
+2
source

Source: https://habr.com/ru/post/1391895/


All Articles