Create text node in a DOM tree

M

Matt

I want to write a method to create text node in a DOM tree.

Here's the method. It works fine for the following xml file.

<?xml version = "1.0"?>
<person>
<name></name>
<age></age>
</person>

//the caller will be...
String xmlFile = "mydoc.xml";
doc = getDocumentFromFile(xmlFile);
Element root = doc.getDocumentElement();
setTextNode(root,"name","Joe");
setTextNode(root,"age","20");

However, it doesn't work anymore if the XML file structure has changed
as follows:

<?xml version = "1.0"?>
<persons>
<person>
<name></name>
<age></age>
</person>
<person>
<name></name>
<age></age>
</person>
</persons>

The parameter Element e in setTextNode(...) cannot be root anymore, we
need to
go to one level deeper. And how to know which level to add??

/**
Given a tag name and a tag value, create a text node in the DOM tree
*/
public static void setTextNode(Element e, String aTagName, String
aTagValue)
{
NodeList children = e.getChildNodes();
for (int i=0; i<children.getLength(); i++)
{ Node childNode = children.item(i);
if (childNode instanceof Element)
{ Element childElement = (Element)childNode;
if (childElement.getTagName().equals(aTagName))
{ Text textNode = doc.createTextNode(aTagValue);
childElement.appendChild(textNode);
}
}
}
}

In other words, the Java program needs to be changed when XML
structure has changed. This is
tedious process. I know we need to parse the tree level by level in
DOM tree. But are there
any other alternatives?

Please advise. Thanks!!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top