1

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");
  • The `winforms` tag isn't really relevant here and _"But it doesn't work"_ isn't helpful. –  Jun 26 '21 at 06:07
  • Does this answer your question? [How to modify existing XML file with XmlDocument and XmlNode in C#](https://stackoverflow.com/questions/2558787/how-to-modify-existing-xml-file-with-xmldocument-and-xmlnode-in-c-sharp) – Amit Verma Jun 26 '21 at 06:18
  • 1
    You need to get the row node using following : XmlNode rowNode = rootNode.SelectSingleNode("row");. The IP is an attribute and your code is adding as an node. – jdweng Jun 26 '21 at 07:53

1 Answers1

1

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");
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Yair I
  • 1,133
  • 1
  • 6
  • 9