Reputation: 57
I got an existing XML file
<Customer>
<PrivateCustomer>
<Adresse>USA</Adresse>
<Phone>12345678</Phone>
<Name>John</Name>
<Age>20</Age>
<Sex>Man</Sex>
<Contract> <Contract/>
</PrivateCustomer>
<PrivateCustomer>
<Adresse>Canada</Adresse>
<Phone>12345678</Phone>
<Name>Peter</Name>
<Age>20</Age>
<Sex>Woman</Sex>
<Contract> <Contract/>
</PrivateCustomer>
<Customer>
In my C# GUI i can select the Names from the xml file in a ComboBox. I want to modify my XML file, where i can change the content of the "Contract" Element where the Name Element = "John".
Ex.
<Customer>
<PrivateCustomer>
<Adresse>USA</Adresse>
<Phone>12345678</Phone>
<Name>John</Name>
<Age>20</Age>
<Sex>Man</Sex>
<Contract>Sold<Contract/>
</PrivateCustomer>
<PrivateCustomer>
<Adresse>Canada</Adresse>
<Phone>12345678</Phone>
<Name>Peter</Name>
<Age>20</Age>
<Sex>Woman</Sex>
<Contract> <Contract/>
</PrivateCustomer>
<Customer>
How can i do it?
Upvotes: 0
Views: 194
Reputation: 101681
To modify an existing element first get the selected name, for example in SelectedIndexChanged
event of ComboBox
the use LINQ to XML:
var selectedName = comboBox1.SelectedItem.ToString();
var xDoc = XDocument.Load("path");
var cust = xDoc.Descendants("PrivateCustomer")
.FirstOrDefault(x => (string)x.Element("Name") == selectedName);
if(cust != null)
{
// edit Customer
cust.Element("Contract").Value = "some value..";
}
xDoc.Save("path"); // save the xml file
Upvotes: 0
Reputation: 864
Try Modify XML existing content in C#, the accepted answer has an example where you can search for an element and alter it's value.
XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");
Upvotes: 1