Click here to Skip to main content
15,949,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an XML file as below
XML
<?xml version="1.0"?>
<equipments>
  <equipment name="DA-001">
    <plant>Brazil</plant>
  </equipment>
  <equipment name="VERIGY-93K_PSL-032">
    <plant>Brazil</plant>
  </equipment>
  <equipment name="BA-1500-002">
    <plant>Muar</plant>
  </equipment>
</equipments>


I need to append items to this XML via some C# code, however I cannot append and retaining same XML format

C#
XmlDocument doc = new XmlDocument();
doc.Load(history);

XmlNode equipment = doc.CreateElement("equipment");
XmlAttribute name = doc.CreateAttribute("name");
name.Value = textBox.Text;
equipment.Attributes.Append(name);
doc.DocumentElement.AppendChild(equipment);

XmlNode plant = doc.CreateElement("plant");
plant.InnerText = cmbPlant.SelectedItem.ToString();
doc.DocumentElement.AppendChild(plant);
doc.Save("Equipment.xml");


The above code is appending as follows: Notice that the plant should be in the equipment node and the equipment is not being closed as the previous XML contents.

XML
<?xml version="1.0"?>
<equipments>
  <equipment name="DA-001">
    <plant>Brazil</plant>
  </equipment>
  <equipment name="VERIGY-93K_PSL-032">
    <plant>Brazil</plant>
  </equipment>
  <equipment name="BA-1500-002">
    <plant>Muar</plant>
  </equipment>
  <equipment name="This_Equipment_added" />
  <plant>USA</plant>
</equipments>
Posted

1 solution

Your problem is that you are adding both 'equipment' and 'plant' as child of the root element...
C#
doc.DocumentElement.AppendChild(equipment);
doc.DocumentElement.AppendChild(plant);

Change the second line to this:
C#
equipment.AppendChild(plant);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900