asp.net C # Operations XML document implementation code

Source: Internet
Author: User
The code is as follows Copy Code

XmlDocument xmldoc = new XmlDocument ();
Add XML declaration paragraph at the top of XML document
XmlNode XmlNode = xmldoc. CreateNode (Xmlnodetype.xmldeclaration, "", "");
XmlDoc. AppendChild (XmlNode);
To create a root node
XmlElement root = xmldoc. createelement ("root");
Root. innertext = "I am the root node";
XmlDoc. AppendChild (root);

XmlDoc. Save (@ "D:my documentsvisual Studio 2010projectswebapplication2webapplication2test.xml");

The resulting XML is like this

The code is as follows Copy Code

<?xml version= "1.0"?>
<root> I am the root node </root>

Another way to create XML

The code is as follows Copy Code

XmlDocument xmldoc = new XmlDocument ();
XmlDoc. Loadxml (
"<?xml version=" 1.0 "encoding=" Utf-8 "?>" +
"<root> I am the root node </root>"
);
XmlDoc. Save (@ "D:my documentsvisual Studio 2010projectswebapplication2webapplication2test.xml");

Reading XML

XML is as follows

The code is as follows Copy Code

<?xml version= "1.0" encoding= "Utf-8"?>
<root id= "root" >
<list num= "0" >
<name type= "string" >minglecun</name>
<age type= "Number" >55</age>
</list>
<list num= "1" >
<name type= "string" >huluwa</name>
<age type= "Number" >1</age>
</list>
</root>

XmlDocument xmldoc = new XmlDocument ();
XmlDoc. Load (@ "D:my documentsvisual Studio 2010projectswebapplication2webapplication2test.xml");
Read a node
XmlNode XmlNode = xmldoc. selectSingleNode ("//root");
Console.WriteLine (XmlNode. INNERXML);
Console.WriteLine ("------------------------------------------------");
XmlNode xmlnode1 = xmldoc. selectSingleNode ("//root//list");
Console.WriteLine (Xmlnode1. INNERXML);
Console.WriteLine ("------------------------------------------------");
//
XmlNodeList Xn0 = xmldoc. selectSingleNode ("//root"). ChildNodes;
foreach (XmlNode node in xn0)
{
Console.WriteLine ("========" +node). Name);
           }

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.