C# 创建XML并输出XML

 最近在处理移动端护理通信,不同平台之间使用XML文件进行相互通信。下面是简单的创建XML和输出XML文件代码:

 1 //用C#创建XML
 2             XmlDocument doc = new XmlDocument();
 3             XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "GB2312", null);
 4             doc.AppendChild(dec);
 5             //创建一个根节点(一级)
 6             XmlElement root = doc.CreateElement("First");
 7             doc.AppendChild(root);
 8             //创建节点(二级)
 9             XmlNode node = doc.CreateElement("Seconde");
10             //创建节点(三级)
11             XmlElement element1 = doc.CreateElement("Third1");
12             element1.SetAttribute("Name", "Sam");
13             element1.SetAttribute("ID", "665");
14             element1.InnerText = "Sam Comment";
15             node.AppendChild(element1);
16             XmlElement element2 = doc.CreateElement("Third2");
17             element2.SetAttribute("Name", "Round");
18             element2.SetAttribute("ID", "678");
19             element2.InnerText = "Round Comment";
20             node.AppendChild(element2);
21            
22             root.AppendChild(node);
23             doc.Save(@"d:\bb0.xml");

运行结果如下所示:

<?xml version="1.0" encoding="GB2312"?>
<First>
  <Seconde>
    <Third1 Name="Sam" ID="665">Sam Comment</Third1>
    <Third2 Name="Round" ID="678">Round Comment</Third2>
  </Seconde>
</First>

 

posted @ 2013-01-30 10:51  Peter.Luo  阅读(625)  评论(0编辑  收藏  举报