try {
String data = "<a><b c='d' e='f'>0.15</b></a>";
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(data));
Document document = documentBuilder.parse(is);
NodeList nl = document.getElementsByTagName("b");
Node n = (Node) nl.item(0);
System.out.println(n.getNodeValue());
} catch (Exception e) {
System.out.println("Exception " + e);
}
I am expecting it to print 0.15, but it prints null. Any Ideas?
Edit: This did the trick
if (n.hasChildNodes())
System.out.println(n.getFirstChild().getNodeValue());
else
System.out.println(n.getNodeValue());
The nodeValue property is used to get the text value of a node. The getAttribute() method returns the value of an attribute.
Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files. In General, a DOM parser loads the XML file into the Android memory to parse the XML document.
DOM Parser is the easiest java xml parser to learn. DOM parser loads the XML file into memory and we can traverse it node by node to parse the XML. DOM Parser is good for small files but when file size increases it performs slow and consumes more memory.
The two common ways to parse an XML document are given below: DOM Parser: Parsing the document by loading all the content of the document and creating its hierarchical tree structure. SAX Parser: Parsing based on event-based triggers. It does not require the complete loading of content.
That's because an element in fact has no nodeValue
. Instead it has a text node as a child, which has the nodeValue
you want.
In short, you'll want to getNodeValue()
on the first child of the element node.
Sometimes the element contains multiple text nodes, as they do have a maximum size, in which case you'll need something á la this, from the page linked earlier:
public static String getNodeValue(Node node) {
StringBuffer buf = new StringBuffer();
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node textChild = children.item(i);
if (textChild.getNodeType() != Node.TEXT_NODE) {
System.err.println("Mixed content! Skipping child element " + textChild.getNodeName());
continue;
}
buf.append(textChild.getNodeValue());
}
return buf.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With