教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 C# 写入XML文档的三种方法与代码实例

C# 写入XML文档的三种方法与代码实例

发布时间:2016-04-20   编辑:jiaochengji.com
本文介绍使用LINQ to XML对XML进行操作的方法,分别使用LINQ to XML 的XDocument类、XmlTextWriter类、XmlDocument类实现。有需要的朋友,参考下吧。

要写入的XML文档内容:
 

<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<Contact id="01">
<Name>Daisy Abbey</Name>
<Gender>female</Gender>
</Contact>
</Contacts>

来看使用三个类,实现写入Xml文档的例子吧。

首先,使用XmlDocument类的例子。
 

var xmlDoc = new XmlDocument();
//Create the xml declaration first
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
//Create the root node and append into doc
var el = xmlDoc.CreateElement("Contacts");
xmlDoc.AppendChild(el);
// Contact
XmlElement elementContact = xmlDoc.CreateElement("Contact");
XmlAttribute attrID = xmlDoc.CreateAttribute("id");
attrID.Value = "01";
elementContact.Attributes.Append(attrID);
el.AppendChild(elementContact);
// Contact Name
XmlElement elementName = xmlDoc.CreateElement("Name");
elementName.InnerText = "Daisy Abbey";
elementContact.AppendChild(elementName);
// Contact Gender
XmlElement elementGender = xmlDoc.CreateElement("Gender");
elementGender.InnerText = "female";
elementContact.AppendChild(elementGender);
xmlDoc.Save("test1.xml");

第二个,使用LINQ to XML 的XDocument类的例子。
 

var doc = new XDocument(
new XElement("Contacts",
new XElement("Contact",
new XAttribute("id", "01"),
new XElement("Name", "Daisy Abbey"),
new XElement("Gender", "female")
)
)
);
doc.Save("test2.xml");

第三个,使用XmlTextWriter类的例子。
 

String filename = String.Concat("test3.xml");
using (StreamWriter sw = new StreamWriter(filename))
{
// Create Xml Writer.
XmlTextWriter xmlWriter = new XmlTextWriter(sw);
// 也可以使用public XmlTextWriter(string filename, Encoding encoding)来构造
// encoding默认为 UTF-8.
//XmlTextWriter writer = new XmlTextWriter("test3.xml", null);
// Set indenting so that its easier to read XML when open in Notepad and such apps.
xmlWriter.Formatting = Formatting.Indented;
// This will output the XML declaration
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Contacts");
xmlWriter.WriteStartElement("Contact");
xmlWriter.WriteAttributeString("id", "01");
xmlWriter.WriteElementString("Name", "Daisy Abbey");
xmlWriter.WriteElementString("Gender", "female");
// close contact </contact>
xmlWriter.WriteEndElement();
// close contacts </contact>
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}

说明:
在实现c#写入xml文件的方法中,LINQ to XML相对简便一些。有兴趣的朋友,还可以参考下C#生成Xml文档的三种方法。
有兴趣的朋友,可以动手测试下,看看各自的效果究竟有哪些不同,多注意下细节,有利于提高c#编程水平。

您可能感兴趣的文章:
C# 写入XML文档的三种方法与代码实例
C# 生成XML文档的三种方法与代码实例
c# 解析XML文件的方法总结
php操作xml的各种方法解析
C#读写xml文件的简单例子
Go基础学习记录之如何解析并生成XML
php解析XML文档属性并编辑的代码
Java生成 Word文档的并打印解决方案
php解析xml文件的四种方法举例
php解析XML数据的一段代码

[关闭]
~ ~