快捷搜索:

C#使用XmlTextWriter类对XML文档进行写入的三种方法

我在曩昔的文章中先容了若何应用XmlDocument类对XML进行操作,以及若何应用LINQ to XML对XML进行操作。它们分手应用了XmlDocument类和XDocument类。在本文中,我再先容一个类,XmlTextWriter。我们分手用这三个类将同样的xml内容写入文档,看一看哪种写法最直不雅、简便。

我们要写入的XML文档内容为

xml version="1.0" encoding="UTF-8"?>

Contacts>Contact id="01">

Name>Daisy AbbeyName>Gender>femaleGender>

Contact>Contacts>

(1)应用XmlDocument类:

var xmlDoc = new XmlDocument();

//Create the xml declaration firstxmlDoc.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 GenderXmlElement elementGender = xmlDoc.CreateElement("Gender");

elementGender.InnerText = "female";elementContact.AppendChild(elementGender);

xmlDoc.Save("test1.xml");

(2)应用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");

(3) 应用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 declarationxmlWriter.WriteStartDocument();

xmlWriter.WriteStartElement("Contacts");

xmlWriter.WriteStartElement("Contact");

xmlWriter.WriteAttributeString("id", "01");

xmlWriter.WriteElementString("Name", "Daisy Abbey");xmlWriter.WriteElementString("Gender", "female");

// close contact

xmlWriter.WriteEndElement();// close contacts

xmlWriter.WriteEndElement();

xmlWriter.WriteEndDocument();

xmlWriter.Close(); }

从上面的代码基础上照样可以看出来,应用LINQ to XML是最简便的。

转自:http://www.cnblogs.com/jfzhu/archive/2012/12/04/2800656.html

您可能还会对下面的文章感兴趣: