简体   繁体   中英

Add a new element with node childs in a XML file in c#

I have a xml that is something like this:

<Servers>
  <MyNewServer>
    <Host>10.10.10.2</Host>
    <Port>12</Port>
    <User>MyUser</User>
    <Password>NkbgKnF9g96EYgxG3qRdCNY2KR6Xd5+0uqpY9KOCl4k=</Password>
  </MyNewServer>
</Servers>

I'm trying to add a new server below of "NyNewServer" label and add the same child elements in blank (Host, Port, User and Password).

I'm adding now a new element of server but is not with the correct format is displayed horizontal instead of vertically, and I'm not sure how to add the child elements in blank.

Any idea? I have this:

public void XmlNewInterface(string Server)
{
    //Temporal Solution
    xmldoc.Load(XMLInterfacesFile);            
    XmlElement record = xmldoc.CreateElement(Server);
    record.InnerText = Guid.NewGuid().ToString();
    xmldoc.DocumentElement.AppendChild(record);

    xmldoc.Save(XMLInterfacesFile);
}

Thanks

I prefer Linq to Xml , it simplifies building/constructing Xml. You just need these lines.

var doc = XDocument.load(inputfile);

doc.Descendants("Servers").First()
    .Add( new XElement("OneMoreServer",  new [] { 
        new XElement("Host"), 
        new XElement("Port"),
        new XElement("MyUser"),
        new XElement("Password")    
    })); 

Output

<Servers>
    <MyNewServer>
        <Host>10.10.10.2</Host>
        <Port>12</Port>
        <User>MyUser</User>
        <Password>NkbgKnF9g96EYgxG3qRdCNY2KR6Xd5+0uqpY9KOCl4k=</Password>
    </MyNewServer>
    <OneMoreServer>
        <Host />
        <Port />
        <MyUser />
        <Password />
    </OneMoreServer>
</Servers>

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM