Append Nodes to existing XML File/Document .net 1.1

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a XML file that I need to append child nodes to. Here is an example of
that file:

<root>
<item>
<stuff1>The Stuff for 1</stuff 1>
<stuff2>The stuff for 2</stuff 2>
</item>
<item>
<otherstuff1>The other stuff for 1</otherstuff1>
<otherstuff2>The other stuff for 2</otherstuff2>
</item>
</root>

I need to append a node to each <item> then write it back to the file. What
is the best way to do this? Thank you

Daniel C. DiVita
 
I think the answer depends on the scope of your requirements. If you
expect more changes like this in future, it would be a good idea to
create a simple xslt stylesheet to append the node and apply the
transformation in code. This way, if your requirement changes, you
just need to edit the xslt.
Another way to implement this would be to load the document in
xmldocument class and coding the changes (use .AppendChild() method).

Latish
 
It will be pretty rare that we will need to do this again. I understand that
I I could use the appendChild() method I was looking for an example, if
possible. Something where I would append the node then write to the file.

Thank you for your reply.

Daniel
 
without testing:

XmlDocument X = new XmlDocument () ;
X.Load ("OldXmlFile.xml") ;
for (XmlNode N = X.DocumentElement.FirsChild ; N != null ; N =
N.NextSibling)
{
if (N.NodeType != XmlNodeType.Element) continue ;
if (N.Name != "item") continue ;
XmlNode NewNode = X.CreateElement("NewChild") ;
NewNode.InnerText="WhatEver";
N.AppendChild(NewNode) ;
}
X.Save ("NewXmlFile.xml") ;
 
Here is a simple snippet
If you want to add a new child to each <Item>, below is a sample.
If you want to add a new sibling to each <item>, use the commented
line of code and comment out.existingNode.AppendChild(newNode );

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\test\xml1.xml");
XmlNodeList xmlNodeList1 = xmlDoc.SelectNodes("//item");
XmlNode newNode;
foreach (XmlNode existingNode in xmlNodeList1 )
{
newNode = xmlDoc.CreateElement("newItem");

existingNode.AppendChild(newNode ); //
to add child to <item>
//existingNode.ParentNode.InsertAfter(newNode,
existingNode); //to add sibling to <item>
}
xmlDoc.Save(@"C:\test\xml2.xml");
 
Back
Top