Hey,
I'm trying to make some simple XML with Java and org.w3c.dom, but I got stuck when I try to append a child to a child, something like this:
<root>
<child>
<childOfTheChild>Some text</childOfTheChild>
</child>
</root>
I tried quite some variations of this (like first appending the child and than creating childOfTheChild etc.):
Element root = doc.getDocumentElement();
Element child = doc.createElement("child");
Element childOfTheChild = doc.createElement("childOfTheChild ");
Text st = doc.createTextNode("Some text");
childOfTheChild.appendChild(st);
child.appendChild(childOfTheChild );
root.appendChild(child);
And I always get the same result, which is:
<root>
<child>null</child>
</root>
Is there a problem in this code or it might be something else?
Edit:
Printing function works ok with some test XMLs otherwise... So, the function without some beauty corrections:
//Call System.out.println( print(dokument.getFirstChild()) );
private String print(Node node) {
String txt = ""; //xml string presentation
//Get the primary node name and any existing attributes, like <myNode att1='some val'>
if (node.getNodeType() == node.ELEMENT_NODE)
{
//The name
txt += "<" + node.getNodeName();
//Insert the attributes
if (node.hasAttributes())
{
NamedNodeMap atts = node.getAttributes();
for (int i = 0; i < atts.getLength(); i++) {
Node atts = atts.item(i);
txt += " " + atts.getNodeName() + " = '" + atts.getNodeValue() + "'";
}
}
txt += ">\n";
}
int nChilds = -1;
//Get any existing child nodes, so the <root><child1></child1></root>
if (node.hasChildNodes())
{
NodeList childs = node.getChildNodes();
nChilds = childs.getLength();
if (nChilds == 1)
{
txt += childs.item(0).getNodeValue();
}
else
{
for (int j = 0; j < nChilds; j++) {
txt += print(childs.item(j));
}
}
}
//And the ending of the primary node, like </root>
if (node.getNodeType() == node.ELEMENT_NODE)
{
txt += "</" + node.getNodeName();
txt += ">\n";
}
return txt;
}