XML document operation highlights (Article C ),

Source: Internet
Author: User

XML document operation highlights (Article C ),

When JSON is not popular, xml has always been the mainstream medium for storing configuration information for programs. Especially for small data tables, xml is a good choice. Therefore, operations that are often involved are nothing more than adding, deleting, modifying, and querying data, this blog briefly summarizes these commonly used operations.

File Loading

SelectNodes (), SelectSingleNode () node Acquisition Algorithm

Create XML document and set element values

XmlReader and XmlWriter

DataSet and XML data

Linq to XML

XML serialization and deserialization

File Loading
  • Load XML by path
XmlDocument xmlDoc = new XmlDocument (); xmlDoc. load (fileName); // file path or URL address Console. writeLine (xmlDoc. innerXml); Console. writeLine ("==================== split lines with forced cells ========================= "); xmlDoc. load ("http://feed.cnblogs.com/blog/picked/rss"); // RSS Console of blog garden excellent posts. writeLine (xmlDoc. innerXml );

  • Load through file stream
   using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))   {       XmlDocument xmlDoc = new XmlDocument();       xmlDoc.Load(stream);       Console.WriteLine(xmlDoc.InnerXml);   }

The Load () method also loads some methods, and there are other ways to Load XML documents, such as LoadXml () to directly Load an XML string

SelectNodes (), SelectSingleNode () node acquisition method <? Xml version = "1.0" encoding = "UTF-8"?> <Names> <Name> <FirstName> John </FirstName> <LastName> Smith </LastName> </Name> <FirstName> James </FirstName> <LastName> white </LastName> </Name> </Names>XML file
  • Use the SelectNodes (string XPath) method of the xpath expression to obtain the node list; SelectSingleNode (string xpath) to obtain the first matched node.
XmlNodeList xmlNodes = xmlDoc. selectNodes ("/Names/Name"); // The first slash must be the root node foreach (XmlNode item in xmlNodes) {Console. writeLine (item. innerXml);} Console. writeLine ("================================== "); xmlNode xmlNode = xmlDoc. selectSingleNode ("/Names/Name"); Console. writeLine (xmlNode. innerXml); Console. writeLine (xmlNode ["LastName"]. innerText); // obtain the subnode

  • Set node feature value to search nodes
<Root> <Item Id = "1" Grade = "1"> Zhang San </Item> <Item Id = "2" Grade = "1"> Li Si </Item> <item Id = "3" Grade = "2"> Wang Wu </Item> <Item Id = "4" Grade = "3"> Zhao Liu </Item> </Root>
XmlNodeList xmlNodes = xmlDoc. selectNodes ("/Root/Item [@ Grade = '1']"); // The XPath expression gets the attribute value information foreach (XmlNode item in xmlNodes) of the node to be set) {Console. writeLine (item. innerText );}

  • Obtain the nth Node
XmlNode xmlNode = xmlDoc. selectSingleNode ("/Root/Item [position () = 3]"); // obtain the N-th node (in the order of XML nodes) Console. writeLine (xmlNode. innerText); Console. writeLine ("=============================== "); xmlNodeList xmlNodes = xmlDoc. selectNodes ("/Root/Item [position () <= 3]"); // obtain the node from the first node to the nth node (foreach (XmlNode item in xmlNodes) {Console. writeLine (item. innerText);} Console. writeLine ("=========================="); xmlNodes = xmlDoc. selectNodes ("/Root/Item [position ()> 2]"); // obtain a node greater than Nth (in the order of XML nodes) foreach (XmlNode item in xmlNodes) {Console. writeLine (item. innerText );}

Create XML document and set element values
XmlDocument xmlDoc = new XmlDocument (); XmlNode rootNode = xmlDoc. createElement ("Root"); // create a node xmlDoc. appendChild (rootNode); Console. writeLine (xmlDoc. innerXml); Console. writeLine ("==================== split lines with forced cells ========================= "); xmlNode node = xmlDoc. createElement ("Item"); XmlAttribute attribute = xmlDoc. createAttribute ("Id"); // create a node attribute. value = "1"; // set the feature Value node. attributes. append (attribute); node. innerText = "Zhang San"; rootNode. appendChild (node); Console. writeLine (xmlDoc. innerXml); Console. writeLine ("==================== split lines with forced cells ========================= "); node = xmlDoc. createElement ("Item"); attribute = xmlDoc. createAttribute ("Id"); attribute. value = "2"; node. attributes. append (attribute); node. innerText = "Li Si"; rootNode. appendChild (node); Console. writeLine (xmlDoc. innerXml );
XmlDoc. Save (fileName); // Save it to a file

XmlReader and XmlWriter

XmlReader performs XML operations faster than XmlDocument and consumes less memory (you can write a test to verify it). However, XmlReader needs to manually determine the element type, which is a little more painful than XmlDocument.

Using (XmlWriter xmlWriter = XmlWriter. create (fileName) {xmlWriter. writeStartDocument (); // starts writing to the xml document xmlWriter. writeStartElement ("users"); xmlWriter. writeStartElement ("user"); xmlWriter. writeAttributeString ("Id", "42"); xmlWriter. writeString ("Zhang San"); xmlWriter. writeEndElement (); xmlWriter. writeStartElement ("user"); xmlWriter. writeAttributeString ("Id", "39"); xmlWriter. writeString ("Li Si"); xmlWriter. writeEndDocument (); // end writing to the xml document} using (XmlReader xmlReader = XmlReader. create (fileName) {while (xmlReader. read () {if (xmlReader. nodeType = XmlNodeType. element) // Element type {Console. writeLine (xmlReader. name); // element Name if (xmlReader. hasAttributes) {Console. writeLine (xmlReader. getAttribute ("Id"); // element name} Console. writeLine (xmlReader. readOuterXml (); // get all the sub-content of the node }}}

DataSet and XML data

Read data to the DataSet through XmlReader

   using (XmlReader xmlReader = XmlReader.Create(fileName, new XmlReaderSettings()))   {       DataSet ds = new DataSet();       ds.ReadXml(xmlReader);       DataTable dt = ds.Tables[0];       for (int i = 0; i < dt.Rows.Count - 1; i++)       {           object[] items = dt.Rows[i].ItemArray;           Console.WriteLine(string.Join(" ", items));       }   }

It is also common to save data tables to XML files.

DataSet ds = new DataSet (); DataTable dt = new DataTable (); dt. columns. add (new DataColumn ("Id", Type. getType ("System. int32 "); dt. columns. add (new DataColumn ("Grade", Type. getType ("System. int32 "); dt. columns. add (new DataColumn ("Name", Type. getType ("System. string "); DataRow dr = dt. newRow (); dr ["Id"] = 9999; dr ["Grade"] = 3; dr ["Name"] = "Sun Qi"; dt. rows. add (dr); ds. tables. add (dt); ds. tables [0]. tableName = "Student"; // each table is the first subnode ds under the root node. writeXml (fileName );

Linq to XML

Quick and easy to operate XML operations through linq

// Query XDocument xdoc = XDocument. load (fileName); var query = from item in xdoc. descendants ("Item") select new {Id = item. attribute ("Id "). value, Name = item. value}; foreach (var item in query) {Console. writeLine (item. id + "" + item. name );}
// Add XDocument xdoc = XDocument. Load (fileName); XElement xele = new XElement ("Item", "Wu ten? "); // Create a node xele. setAttributeValue ("Id", 10); // set the node feature value xdoc. element ("Root "). add (xele); xdoc. save (fileName );
// Delete XDocument xdoc = XDocument. load (fileName); XElement xele = xdoc. descendants ("Item "). where (c => c. attribute ("Id "). value. equals ("10 ")). firstOrDefault (); xele. remove (); xdoc. save (fileName );
// Modify XDocument xdoc = XDocument. load (fileName); XElement xele = xdoc. descendants ("Item "). where (c => c. attribute ("Id "). value. equals ("1 ")). firstOrDefault (); xele. value = "Current Year"; xdoc. save (fileName );
XML serialization and deserialization
// Serialize var student = new Student () {Id = 1, Grade = 2, Name = ""}; XmlSerializer serializer = new XmlSerializer (typeof (Student); serializer. serialize (Console. out, student );
// Deserialization string input = "<? Xml version = \ "1.0 \" encoding = \ "gb2312 \"?> <Student> <Id> 1 </Id> <Grade> 2 </Grade> <Name> Li Si </Name> </student> "; using (StringReader sr = new StringReader (input) {XmlSerializer serializer = new XmlSerializer (typeof (Student); Student student = (Student) serializer. deserialize (sr); Console. writeLine (student. name );}

Additional reading

http://www.dotnetcurry.com/linq/564/linq-to-xml-tutorials-examples

http://www.tutorialspoint.com/linq/linq_xml.htm

https://msdn.microsoft.com/en-us/library/mt693062.aspx

http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html

http://www.codeproject.com/Articles/24376/LINQ-to-XML

http://csharp.net-tutorials.com/xml/reading-xml-with-the-xmlreader-class/

https://msdn.microsoft.com/zh-cn/library/58a18dwa(v=vs.120).aspx

http://csharp.net-informations.com/xml/xml-de-serialization.htm

Related Article

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.