Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

adding new attribute to an existing xml file

Hi

This is my first post to this group and Im hoping to get some suggestions as Im completely exhausted trying to resolve my query.

I have a test.xml file whose structure is such:

<Top>
<Tags>
<Tag id="123" name="Home">
<Value>Inner Text</Value>
</Tag>
</Tags>
</Top>

Now using the JAXP DocumentBuilder I am able to access the attribute @name from the <Tag> node. I then want to insert a new attribute @new="some value" to this <Tag> node. But despite trying out several options Im not able to. I want to do something similar with the <Value> node as well and append some InnerText to the existing one.

My code so far is:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(test.xml);

NodeList list = doc.getElementsByTagName("Tag");

for(int i=0; i<list.getLength();i++){
Element tagNode = (Element)list.item(i); //<Tag>
nm = tagNode.getAttributes();

for(int j=0;j<nm.getLength();j++){
Node ndNm = nm.item(j); // id, name --attributes names
nodeLocNm = ndNm.getNodeName();

if(nodeLocNm.equals(new String("name"))){
String nodeVal = nm.item(j).getNodeValue(); //@name
String newRes = "new value";
tagNode.setAttribute("new", "new value");
}
}
}

----------------

Of course no attribute @name gets added to test.xml.

Could someone please help.

Thanks in advance to everyone for helping out!
Rahil
[1898 byte] By [rqamar] at [2007-11-11 6:33:49]
# 1 Re: adding new attribute to an existing xml file
That looks like a good start. But you only changed the representation in memory of the XML. Your next step should be to write your Document back out to disk.
DrClap at 2007-11-11 23:28:45 >