簡體   English   中英

在C#中將元素從一個XML文件復制和重命名為另一個XML文件

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

我想將數據從我的asp.net GUI添加到xml文件中,所以我在GUI中有一個文本框。

因此,如果用戶輸入“ IL”,那么我想以這種方式添加一個部分

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

XML檔案:

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

注意:

每當我在此處添加新部分時,內部元素都是恆定的,即以下值始終是相同的。

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

我正在尋找如何使用LINQ to XML做到這一點?

由於要添加的節點的唯一可變部分是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"))
    );
}

現在,當您想使用新員工數據更新現有XML時,可以通過以下方式進行:

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

新員工節點將被添加到現有員工節點。

有關XML樹的創建與LINQ到XML的更多信息(因為這是我們在這里處理),在網上查詢指南這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM