[WebMethod(Description = "向空XML自己添加数据")]
public XmlDocument XD()
{
XmlDocument xmldoc = new XmlDocument();
//加入XML的声明段落,<?xml version="1.0" encoding="utf-8"?>
xmldoc.AppendChild(xmldoc.CreateXmlDeclaration("1.0","utf-8",null));
//XmlDeclaration xmldecl = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
//xmldoc.AppendChild(xmldecl);
//创建根元素
XmlElement xmlelem = xmldoc.CreateElement("","Employees","");
xmldoc.AppendChild(xmlelem);
//设置根元素
XmlNode root = xmldoc.SelectSingleNode("Employees");//查找
//添加第一个子元素
XmlElement xe_1 = xmldoc.CreateElement("Employees");
xe_1.SetAttribute("Ename", "第一个人");
xe_1.SetAttribute("Esex", "男");
xe_1.SetAttribute("Eage", "17岁");
root.AppendChild(xe_1);
//添加第一个子元素的子元素
XmlElement xe_1_1 = xmldoc.CreateElement("Node");
xe_1_1.SetAttribute("BName", "英国");
xe_1_1.SetAttribute("BSN", "Vec.1");
XmlElement xe_1_2 = xmldoc.CreateElement("title");
xe_1_2.InnerText = "C#学习";
XmlElement xe_1_3 = xmldoc.CreateElement("Autor");
xe_1_3.InnerText = "张三";
XmlElement xe_1_4 = xmldoc.CreateElement("price");
xe_1_4.InnerText = "65";
xe_1.AppendChild(xe_1_1);
xe_1.AppendChild(xe_1_2);
xe_1.AppendChild(xe_1_3);
xe_1.AppendChild(xe_1_4);
//添加第二个子元素
XmlElement xe_2 = xmldoc.CreateElement("Employees");
xe_2.SetAttribute("Ename", "第二个人");
xe_2.SetAttribute("Esex", "女");
xe_2.SetAttribute("Eage", "17岁");
root.AppendChild(xe_2);
//添加第二个子元素的子元素
XmlElement xe_2_1 = xmldoc.CreateElement("Node");
xe_2_1.SetAttribute("BName", "英国");
xe_2_1.SetAttribute("BSN", "Vec.2");
XmlElement xe_2_2 = xmldoc.CreateElement("title");
xe_2_2.InnerText = "ASP学习";
XmlElement xe_2_3 = xmldoc.CreateElement("Autor");
xe_2_3.InnerText = "李四";
XmlElement xe_2_4 = xmldoc.CreateElement("price");
xe_2_4.InnerText = "88";
xe_2.AppendChild(xe_2_1);
xe_2.AppendChild(xe_2_2);
xe_2.AppendChild(xe_2_3);
xe_2.AppendChild(xe_2_4);
//返回xml
return xmldoc;
}
<?xml version="1.0" encoding="UTF-8"?>
-<Employees> -<Employees Eage="17岁" Esex="男" Ename="第一个人"> <Node BSN="Vec.1" BName="英国"/> <title>C#学习</title> <Autor>张三</Autor> <price>65</price> </Employees> -<Employees Eage="17岁" Esex="女" Ename="第二个人"> <Node BSN="Vec.2" BName="英国"/> <title>ASP学习</title> <Autor>李四</Autor> <price>88</price> </Employees> </Employees>