Hi,
Node value always coming back as Null given XML snippet and code below (scroll right to end to see the XML). It is obviously getting value of the Element, rather than the text - pse assist!! Have looked at APIs, can't work it out. thanks v.much
If a Node looks like
<item>hi</item>
I would expect node.getValue() to return the
String "hi". But it is returning null.
CODE:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.*;
//import org.w3c.dom.DOMException;
import java.io.*;
public class DomEcho {
static Document document;
public static void main(String argv[])
{
if (argv.length != 1) {
System.err.println("Usage:
java DomEcho filename");
System.exit(1);
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//factory.setValidating(true);
//factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse( new File(argv[0]) );
Element xmlRoot = document.getDocumentElement();
String rootName = xmlRoot.getTagName();
System.out.println ("rootName: " + rootName);
NodeList nl = document.getElementsByTagName("item");
int len = nl.getLength();
System.out.println ("LEN" + len);
for (int i = 0; i<len; i++) {
Node node = nl.item(i);
String nodeVal = node.getNodeValue();
String nodeName = node.getNodeName();
System.out.println ("nodeVal" + nodeVal + "nodeName" + nodeName + "nodeLocalName" + nodeLocalName + "nodeType" + nodeType);
}
} //catch (SAXParseException spe) {
//}
catch (SAXException sxe) {
// Error generated during parsing
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
}
catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
}// main
}// DomEcho
XML:
<?xml version='1.0' encoding='utf-8'?>
<!-- A SAMPLE set of slides -->
<slideshow
title="Sample Slide Show"
date="Date of publication"
author="Yours Truly"
>
<!-- TITLE SLIDE -->
<slide type="all">
<title>Wake up to WonderWidgets!</title>
</slide>
<!-- OVERVIEW -->
<slide type="all">
<title>Overview</title>
<item>Why <em>WonderWidgets</em> are great</item>
<item/>
<item>Who <em>buys</em> WonderWidgets</item>
<item>*auckland?christchurch*</item>
</slide>
</slideshow>