How to Use xmlbeannet to create XML documents

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.