简体   繁体   中英

Copying and Renaming an Element from one XML file to another XML file in c#

I Want to add the data to the xml file from my asp.net GUI.So i have a textbox in GUI.

So if user enters "IL" then i want to add a section in this way

<Employee Location="IL">
    <Male Value="True" />
    <Name Value="xxx" />
</Employee>

XML file:

 <Emp>
  <Employee Location="NJ">
    <Male Value="True" />
    <Name Value="xxx" />
   </Employee>
  <Employee Location="NY">
    <Male Value="True" />
    <Name Value="xxx" />
   </Employee>
</Emp>

Note:

Every time i add a new section here the inner elements are constant ie the following values are always to be same.

<Male Value="True" />
<Name Value="xxx" />

I am looking for how can i achieve this using LINQ to XML?

Since only variable part of node you're adding is Location attribute, you can very easily extract that process to a method, like the following one:

private XElement CreateEmployeeNode(string location)
{
    return new XElement("Employee",
        new XAttribute("Location", location),
        new XElement("Male", new XAttribute("Value", "True")),
        new XElement("Name", new XAttribute("Value", "xxx"))
    );
}

Now when you want to update your existing XML with new employee data, you do it this way:

var document = XDocument.Parse(xmlString); // or .Load, depending how you get XML
var newEmployeeLocation = textBox.Text;
document.Element("Emp").Add(CreateEmployeeNode(newEmployeeLocation));

New employee node will be added to existing ones.

For more information on XML trees creation with LINQ to XML (as this is what we're dealing with here), check online guide here .

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