简体   繁体   English

在C#中将元素从一个XML文件复制和重命名为另一个XML文件

[英]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. 我想将数据从我的asp.net GUI添加到xml文件中,所以我在GUI中有一个文本框。

So if user enters "IL" then i want to add a section in this way 因此,如果用户输入“ IL”,那么我想以这种方式添加一个部分

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

XML file: XML档案:

 <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? 我正在寻找如何使用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: 由于要添加的节点的唯一可变部分是Location属性,因此可以非常轻松地将该过程提取到一种方法中,如下所示:

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: 现在,当您想使用新员工数据更新现有XML时,可以通过以下方式进行:

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 . 有关XML树的创建与LINQ到XML的更多信息(因为这是我们在这里处理),在网上查询指南这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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