Ngọc Huyền
Ngọc Huyền

Reputation: 45

Add data to a row var xmlDocument in C# Winforms

I got a xml File like this and I want to add a /row/var to this file. For example, I want to add name="Test1" value="192.178.123.1" and the xml file will add a /var like <var name="Test1" value="192.178.123.1"/>. How could I do?

<DNS>
  <row>
    <var name="Viettel" value="192.168.1.1"/>
    <var name="Google" value="192.182.11.2" />
    <var name="Singapore" value="165.21.83.88" />
    <var name="Verizon" value="4.2.2.1" />
    <var name="VNPT" value="203.162.4.191" />
    <var name="FPT" value="203.113.131.1" />
    <var name="OpenDNS" value="210.245.31.130" />
    <var name="Cloudflare" value="208.67.222.222" />
    <var name="Norton" value="1.1.1.1" />
    <var name="Viettel" value="198.153.192.1" />
    <var name="Dnsadvantage" value="192.168.1.1" />
    <var name="Hi-Teck" value="1156.154.70.1" />
    <var name="Viettel" value="209.126.152.184" />
  </row>
</DNS>

This is my code currently. But it doesn't work.

XmlDocument xdoc = new XmlDocument();
            xdoc.Load(@"E:\Applications\Visual\C#\Forms\Test\XMLFile1.xml");
            
            XmlNode rootNode = xdoc.DocumentElement;
            XmlNode serverPathNode = xdoc.CreateElement("Test1");
            serverPathNode.InnerText = "192.178.123.1";

            rootNode.AppendChild(serverPathNode);

            xdoc.Save(@"E:\Applications\Visual\C#\Forms\Test\XMLFile1.xml");

Upvotes: 1

Views: 275

Answers (1)

Yair I
Yair I

Reputation: 1133

this is what you need to do (comments inside):

XmlDocument xdoc = new XmlDocument();
xdoc.Load(@"E:\Applications\Visual\C#\Forms\Test\XMLFile1.xml");

//find the row node to be able to add to him more "var" nodes
XmlNode rowNode = xdoc.SelectSingleNode("/DNS/row");
//create new "var" node
XmlNode serverPathNode = xdoc.CreateElement("var");
//the details are attributes and not nodes so we add them as attributes to the var node
XmlAttribute xmlAttribute = xdoc.CreateAttribute("name");
xmlAttribute.Value = "Test1";
serverPathNode.Attributes.Append(xmlAttribute);
xmlAttribute = xdoc.CreateAttribute("value");
xmlAttribute.Value = "192.178.123.1";
serverPathNode.Attributes.Append(xmlAttribute);

//add the var node to the row node
rowNode.AppendChild(serverPathNode);

xdoc.Save(@"E:\Applications\Visual\C#\Forms\Test\XMLFile1.xml");

Upvotes: 1

Related Questions