Penicillin

Hello

I have this file.xml which contains these data:

Code Snippet
< xml version="1.0" standalone="yes" >
- <DocumentElement>
- <MyValues>
<Name>John</Name>
<Occupation>Doctor</Occupation>
<Age>40</Age>
</MyValues>
- <MyValues>
<Name>Smith</Name>
<Occupation>Engineer</Occupation>
<Age>35</Age>
</MyValues>
</DocumentElement>

Q1. How can I delete all nodes when "Occupation=Doctor"
Q2. How can I insert a new node
Thanks


Re: XML and the .NET Framework How to Add/Insert Nodes in XML?

onh1986

I need your help please.



Re: XML and the .NET Framework How to Add/Insert Nodes in XML?

ke1

Hi.

This is a sample of C#.

code for delete node

Code Snippet

XmlDocument doc = new XmlDocument();
doc.Load("filepath + filename");
XmlNode root1 = doc.DocumentElement;
string target = "DocumentElement/MyValues/Occupation";
foreach (XmlNode mn in doc.SelectNodes(target))
{
if (mn.InnerText == "Doctor")
{
root1.RemoveChild(mn.ParentNode);
}
}
doc.Save("filepath + filename");

code for append node

Code Snippet

XmlDocument doc = new XmlDocument();
doc.Load("filepath + filename");
XmlNode root1 = doc.DocumentElement;
XmlElement newEle = doc.CreateElement("MyValues");
newEle.InnerXml = "<Name>John</Name><Occupation>Doctor</Occupation><Age>40</Age>";
root1.AppendChild(newEle);
doc.Save("filepath + filename");





Re: XML and the .NET Framework How to Add/Insert Nodes in XML?

Martin Honnen

Use an XPath expression alike DocumentElement/MyValues[Occupation = 'Doctor'] e.g. with C# you can delete as follows:

Code Snippet

XmlDocument xmlDocument = new XmlDocument();

xmlDocument.Load(@"file.xml");

XmlNodeList valuesToRemove = xmlDocument.SelectNodes(@"DocumentElement/MyValues[Occupation = 'Doctor']");

for (int i = valuesToRemove.Count - 1; i >= 0; i--) {

valuesToRemove[i].ParentNode.RemoveChild(valuesToRemove[i]);

}

xmlDocument.Save("file.xml");






Re: XML and the .NET Framework How to Add/Insert Nodes in XML?

Penicillin

Thank very very much.