Click here to Skip to main content
15,877,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Any help would be greately appreciated. I am trying to figure out a way to add a node to an existing XML file. Here's the situation:

I want to and a new "B" node as the first node - immediately following <A>.
Each time I tried to add the new node, it's appended to the bottom of the node list.
The existing file resembling the following:

<A>
<B>
<C />
<C />
<C />
</B>
<B>
<C />
<C />
<C />
</B>
<B>
<C />
<C />
<C />
</B>
</A>
Posted
Comments
DaveAuld 9-Oct-11 15:07pm    
Post your code snippet for what you have so far......

I do not know which language you are using but for System.Xml you use the XmlNode.InsertBefore[^] Method.
See the example in the documentation.

You want to use InserBefore to add a new node before the first child of <A>.
 
Share this answer
 
v2
Reply to Andre. Thanks for the help. I'm using C Sharp.
And when I use InsertBefore I get the following:

"The reference node is not a child of this node."

Here's the code:


string xmlTemp = "C:\\Users\\User\\Documents\\My Projects\\temp.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlTemp);

XmlNode nodeA = xmlDoc.SelectSingleNode("A");
XmlNode nodeB = xmlDoc.CreateNode(XmlNodeType.Element, "B", null);
XmlNode nodeC = xmlDoc.CreateNode(XmlNodeType.Element, "C", null);

nodeA.InsertBefore(nodeB, xmlDoc.FirstChild);

nodeB.AppendChild(nodeC);

xmlDoc.Save(xmlTemp);
 
Share this answer
 
Comments
André Kraak 9-Oct-11 17:01pm    
If you have a question about or comment on a given solution use the "Have a Question or Comment?" option beneath the solution. When using this option the person who gave the solution gets an e-mail message and knows you placed a comment and can respond if he/she wants.

Please move the content of this solution to the solution you are commenting on and remove the solution.
Thank you.
Problem solved. Thanks, Andre
 
Share this answer
 
Comments
André Kraak 9-Oct-11 17:02pm    
That is nice, perhaps you could post it here so that people with the same problem can use it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900