C# 寫入XML文檔三種方法詳細介紹

來源:互聯網
上載者:User

我在以前的部落格中介紹了如何使用XmlDocument類對XML進行操作,以及如何使用LINQ to XML對XML進行操作。它們分別使用了XmlDocument類和XDocument類。在本文中,我再介紹一個類,XmlTextWriter。我們分別用這三個類將同樣的xml內容寫入文檔,看一看哪種寫法最直觀、簡便。
我們要寫入的XML文檔內容為 複製代碼 代碼如下:<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<Contact id="01">
<Name>Daisy Abbey</Name>
<Gender>female</Gender>
</Contact>
</Contacts>

(1)使用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");

(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 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();
}

從上面的代碼基本上還是可以看出來,使用LINQ to XML是最簡便的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.