Click here to Skip to main content
16,022,333 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi every one,

I am taking XML file as my data base. The data that I want to insert into XML file it is getting inserted.

But now I want to remove a node from that XML file. Here is my XML file content.

XML
<Cluster_list>
  <Cluster>A</Cluster>
  <Cluster>B</Cluster>
  <Cluster>C</Cluster>
</Cluster_list>

Now I want to remove the node which has the value C from that list.

I wrote code like this.
C#
XmlDocument doc = new XmlDocument();
                doc.Load(cluster_path);//Path is given globly

 XmlNode node = doc.SelectSingleNode("/Cluster_list [Cluster='"+cluster_name+"']");

node.ParentNode.RemoveChild(node);


                doc.Save(cluster_path);

Here I will give the value cluster_name=C.

The error is coming at the - doc.Save(cluster_path);
Saying - "invalid xml document the document does not have a root element it does have a root element"

I searched in internet but I didn't got proper solution. So can any body suggest any solution.

Advance Thanks
Arun
Posted
Updated 8-Dec-11 20:00pm
v2

Switch to using XElement ... in LINQ to XML ... makes handling and manipulating XML much easier than using XmlDocument. Plenty of examples on the web.
 
Share this answer
 
I have not worked so much on c# to xml but u can use this :
C#
XmlNode.RemoveChild(XmlNode);

n search about this. this will surely help you. :)
 
Share this answer
 
v2
Comments
RaviRanjanKr 9-Dec-11 5:50am    
A suggestion :- Never use short text words like u instead of 'you' and n instead of 'and'.
arunrv 9-Dec-11 23:46pm    
Please don't use short form of words :)
XmlDocument xml = new XmlDocument();
xml.Load(cluster_path);
XmlNode userNodes = xml.SelectSingleNode("/Cluster_list[Cluster='"+cluster_name+"']");
foreach (XmlNode userNode in userNodes)
{
if (userNode.InnerText == cluster_name)
{
userNodes.RemoveChild(userNode);
}
}
xml.Save(cluster_path);
userNodes = null;
xml = null;
 
Share this answer
 
v4
Comments
Dave Kreskowiak 5-Sep-24 20:05pm    
XElement is easier to use and you're 13 years too late to the discussion.
Member 16360323 6-Sep-24 10:19am    
It doesn't matter how much time has passed, but the solution to the problem.
Richard Deeming 9-Sep-24 4:24am    
An unformatted, unexplained code-dump is never a "solution" to a question!

Also, the RemoveChild method was already mentioned in solution 2, posted back in 2011.

Stick to answering new questions where the OP still needs help, unless you have something new and interesting to add to the discussion. Resurrecting ancient questions with an unexplained code-dump, or with a solution that just repeats what has already been said, will get you banned.

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