在C#中动态添加XMl元素,节点,属性 [英] Adding XMl Element, node, attributes dynamically in C#
本文介绍了在C#中动态添加XMl元素,节点,属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在接受以下概念。我正在使用.Net 2.0 Framework。
我在指定路径中有XML文件。喜欢下面的结构。需要添加员工国家智慧。
Hi,
I am getting strucked in below concept. I am using .Net 2.0 Framework.
I have XML File in specified path. Like Below Structure. Need to add Employee Country Wise.
<?xml version="1.0" encoding="utf-8"?>
<EmployeeList xmlns="http://tempuri.org/format.xsd" key="lank">
<Country id="India">
<Emp Name="X1" address="Y1" id="Z1" />
<Emp Name="X2" address="Y2" id="Z2" />
<Emp Name="X3" address="Y3" id="Z3" />
</Country>
</EmployeeList>
如果国家印度存在,则添加记录在特定国家/地区,将其添加为新国家/地区
If Country India is Exists then add records under specific country else add it as new country.
<?xml version="1.0" encoding="utf-8"?>
<EmployeeList xmlns="http://tempuri.org/format.xsd" key="lank">
<Country id="India">
<Emp Name="X1" address="Y1" id="Z1" />
<Emp Name="X2" address="Y2" id="Z2" />
<Emp Name="X3" address="Y3" id="Z3" />
<Emp Name="X4" address="Y3" id="Z4" /> <!-- Newly Added in existing Country-->
</Country>
</EmployeeList>
如果New Country Come那么输出需要像这样
If New Country Come then Output needs to be like this
<?xml version="1.0" encoding="utf-8"?>
<EmployeeList xmlns="http://tempuri.org/format.xsd" key="lank">
<Country id="India">
<Emp Name="X1" address="Y1" id="Z1" />
<Emp Name="X2" address="Y2" id="Z2" />
<Emp Name="X3" address="Y3" id="Z3" />
</Country>
<Country id="USA">
<Emp Name="X4" address="Y3" id="Z4" /> <!-- Newly Added in seperate country-->
</Country>
</EmployeeList>
推荐答案
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Country");
XmlElement id = doc.CreateElement("Emp");
id.SetAttribute("Name", "A");
id.SetAttribute("Address", "Add1");
root.AppendChild(id);
doc.AppendChild(root);
doc.Save("test.xml");
}
}
如果国家/地区已经存在,则在crate元素中添加条件然后使用else创建新根像这样
And add condition in crate element if country is already exist then use else create new root like this
这篇关于在C#中动态添加XMl元素,节点,属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文