C # manipulating XML

Source: Internet
Author: User

C # manipulating XML

In System.Xml there are classes that can manipulate XMl

(The online record of these classes is really very small, perhaps because the class is more than the introduction of MSDN)

Create a new XML

XmlDocument xmldoc =NewXmlDocument ();
//Add XML declaration paragraph at the head of the XML document
XmlNode XmlNode = xmldoc. CreateNode (Xmlnodetype.xmldeclaration,"","");
XmlDoc. AppendChild (XmlNode);
//Creating the root node
XmlElement root = xmldoc. CreateElement ("Root");
Root. InnerText ="I'm the root node .";
XmlDoc. AppendChild (root);

XmlDoc. Save (@"D:\My documents\visual Studio 2010\projects\webapplication2\webapplication2\test.xml");


The generated XML is like this

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

Another way to create XML

            New XmlDocument ();
XmlDoc. LOADXML (
" <?xml version=\ "1.0\" encoding=\ "utf-8\"?> " +
" <root> I am the root node </root> "
);
XmlDoc. Save (@ "D:\My documents\visual Studio 2010\projects\webapplication2\webapplication2\test.xml "


Read XML

The XML is as follows

<?XML version= "1.0" encoding= "Utf-8"?>
<RootID= "root">
<ListNum= "0">
<nametype= "string">Minglecun</name>
< Agetype= "Number">55</ Age>
</List>
<ListNum= "1">
<nametype= "string">Huluwa</name>
< Agetype= "Number">1</ Age>
</List>
</Root>

XmlDocument xmldoc =NewXmlDocument ();
XmlDoc. Load (@"D:\My documents\visual Studio 2010\projects\webapplication2\webapplication2\test.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 nodeinchXN0)
{
Console.WriteLine ("========"+node. Name);
}





C # manipulating XML

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.