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