The three methods of writing C to XML document are described in detail

  • 2020-05-07 20:20:13
  • OfStack

In a previous blog post, I explained how to operate on XML using the XmlDocument class and XML using LINQ to XML. They use the XmlDocument and XDocument classes, respectively. In this article, I introduce one more class, XmlTextWriter. Let's use these three classes to write the same xml content to the document, and see which is the most intuitive and convenient way to write it.
The XML document we want to write is
 
<?xml version="1.0" encoding="UTF-8"?> 
<Contacts> 
<Contact id="01"> 
<Name>Daisy Abbey</Name> 
<Gender>female</Gender> 
</Contact> 
</Contacts> 

(1) USES XmlDocument class :
 
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) XDocument class using LINQ to XML:
 
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) USES XmlTextWriter class :
 
String filename = String.Concat("test3.xml"); 
using (StreamWriter sw = new StreamWriter(filename)) 
{ 
// Create Xml Writer. 
XmlTextWriter xmlWriter = new XmlTextWriter(sw); 
//  Can also be used public XmlTextWriter(string filename, Encoding encoding) To construct the  
// encoding The default is  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(); 
} 

As you can see from the above code, LINQ to XML is the easiest to use.

Related articles: