I want to add a new line in below "option1 line" at my XML file by c#.my code working correctly but the only problem is my new line write out of "XmlParameters" and "RegParameters" under . Does anybody know how to go to "XmlParameters" to writing my new line?
this is my original XML file:
<?xml version="1.0" encoding="utf-8"?>
<CustomConfiguraton xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ConfigSection Name="Message">
<XmlParameters>
<XmlParam Key="OPTION1" Value="XXX" Option="" />
</XmlParameters>
<RegParameters>
</RegParameters>
</ConfigSection>
<ConfigSection Name="Tcpip">
<XmlParameters>
</XmlParameters>
</ConfigSection
<XmlParameters>
</XmlParameters>
</ConfigSection>
</CustomConfiguraton>
I want to add a line under Option1 in it. additional line is :
<XmlParam Key="OPTION2" Value="XXX" Option="" />
finally, I want to have this XML file:
<?xml version="1.0" encoding="utf-8"?>
<CustomConfiguraton xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ConfigSection Name="Message">
<XmlParameters>
<XmlParam Key="OPTION1" Value="XXX" Option="" />
<XmlParam Key="OPTION2" Value="XXX" Option="" />
</XmlParameters>
<RegParameters>
</RegParameters>
</ConfigSection>
<ConfigSection Name="Tcpip">
<XmlParameters>
</XmlParameters>
</ConfigSection
<XmlParameters>
</XmlParameters>
</ConfigSection>
</CustomConfiguraton>
I try this code but the result is not the same as the things I want and the line added in the end of "ConfigSection Name="Message" and out of "XmlParameters" and "XmlParameters"
const string FILENAME = @"E:\Config.xml";
XDocument doc = XDocument.Load(FILENAME);
XElement type2 = doc.Descendants("ConfigSection").Where(x => (string)x.Attribute("Name") == "Message").FirstOrDefault();
type2.Add(new XElement("XmlParam", new XAttribute("Key", "OPTION2"), new XAttribute("Value", "XXX"), new XAttribute("Option", "")));
doc.Save(@"E:\Config.xml");