Reputation: 367
I am parsing the below XML
using the Dom Parser.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
<Staff id="1">
<firstname>Achyut</firstname>
<lastname>khanna</lastname>
<nickname>Achyut</nickname>
<salary>900000</salary>
</Staff>
</company>
If I only need firstName from the XML why is returning null ?
private String getNodeValue(Node node) {
Node nd = node.getFirstChild();
try {
if (nd == null) {
return node.getNodeValue();
}
else {
getNodeValue(nd);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Upvotes: 1
Views: 2265
Reputation: 12817
Save yourself a lot of code by using XPath instead:
XPath xp = XPathFactory.newInstance().newXPath();
InputSource in = new InputSource(...);
String fn = xp.evaluate("/company/Staff[@id='1']/firstname/text()", in);
System.out.println(fn);
printts:
Achyut
Upvotes: 0
Reputation: 12363
You must fetch the nodelist and then pass the appropriate Node value as parameter when you call your defined function.
NodeList n = item.getElementsByTagName("Staff");
Then call your function
String firstName = getNodeValue(n.item(0));
Upvotes: 1
Reputation: 8096
First of all, I do not recommend parsing XMLs using DOM traversals. I would recommend you to use the OXMs (JaxB or XMLbeans). But still if you are interested in doing it this way:
Here is the code
public class T2 {
public static void main(String []args) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilder db = null;
String xmlString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><company> <Staff id='1'> <firstname>Achyut</firstname> <lastname>khanna</lastname> <nickname>Achyut</nickname> <salary>900000</salary> </Staff></company>";
Document doc = null;
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("firstname");
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i) instanceof Element) {
Node node = (Node) nodes.item(i);
nodes.item(i);
String fName = getCharacterDataFromElement(node);
System.out.println(fName);
}
}
}
private static String getCharacterDataFromElement(Node e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return null;
}
}
The code above prints Achyut
Upvotes: 0