0

I want to generate an xml from existing one but remove one node by Id: My xml is:

<PartyList>
  <Party Id="1" In="true" Out="true"/>
  <Party Id="2" In="true" Out="false"/>
  <Party Id="3" In="true" Out="true"/>
</PartyList>

and tried to select the node by using the following but cant remove it:

xmlNode = xmlDoc.SelectSingleNode("/PartyList/Party[@Id='3']"));

how can I remove it? and is there a better way by using linq to xml?

1 Answer 1

3

Removing selected element from the XmlDocument can be done as follow :

xmlNode = xmlDoc.SelectSingleNode("/PartyList/Partyx[@Id='3']");
xmlNode.ParentNode.RemoveChild(xmlNode);
xmlDoc.Save("path_for_the_updated_file.xml");

Or using LINQ-to-XML's XDocument :

var doc = XDocument.Load("path_to_your_xml_file.xml");
doc.Root
   .Elements("Partyx")
   .First(o => (int)o.Attribute("Id") == 3)
   .Remove();
doc.Save("path_for_the_updated_file.xml");
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer... I did it in for loop so can i keep the original xml and save the new xml in a string value
@user1150331 you can access the string value of the updated XML from OuterXml property of XmlDocument or by calling ToString() on the XDocument : xmlDoc.OuterXml, or doc.ToSring()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.