Xml is also a common basic knowledge point in our daily development. Do you know how to use background code to create an xml document? The following is a demo I have used in my own learning. I hope to help those who need it!
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
// Introduce the namespace
Using System. Xml;
Namespace CreateXmlDemo
{
Class Program
{
Static void Main (string [] args)
{
// Step 1: first create an empty XML document
XmlDocument xdt = new XmlDocument ();
// Step 2: add the XML declaration section to the header of the XML document to create a declared node.
XmlNode xn = xdt. CreateNode (XmlNodeType. XmlDeclaration ,"","");
Xdt. AppendChild (xn );
// Step 3: add comments
XmlComment xmlComm = xdt. CreateComment ("comment content ");
Xdt. AppendChild (xmlComm );
// Step 4: add an element to the XML document/Add a root element
XmlElement xmlement = xdt. CreateElement ("", "student ","");
// Step 5: add an attribute
XmlAttribute xmlAttr = xdt. CreateAttribute ("professional ");
XmlAttr. Value = "computer ";
Xmlement. Attributes. Append (xmlAttr );
Xdt. AppendChild (xmlement );
// Step 6: Add a child element
XmlElement xmlelement2 = xdt. CreateElement ("name ");
XmlText xt = xdt. CreateTextNode ("Zhang zhongxi ");
Xmlelement2.AppendChild (xt );
Xmlement. AppendChild (xmlelement2 );
XmlElement xmlelement3 = xdt. CreateElement ("gender ");
Xt = xdt. CreateTextNode ("male ");
Xmlelement3.AppendChild (xt );
Xmlement. AppendChild (xmlelement3 );
// Step 7: Save the created XML document
Try
{
Xdt. Save (@ "C: \ Users \ Winner \ Desktop \ sample. xml ");
}
Catch (Exception ex)
{
// Realistic error message
Console. WriteLine (ex. Message );
}
Console. ReadKey ();
}
}
}