C # basic methods for reading and writing XML

Source: Internet
Author: User
Method for reading and writing XML files in C # (xmlreader, xmlwriter)

There are several methods available. You can take a look.

Http://fmouz.spaces.live.com/blog/cns! A3e6bf121783821a! 22035. Entry [go] C # the Getting Started Method for reading and writing XML files is known to have an XML file (bookstore. XML) as follows: <? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
</Bookstore> 1. Insert a <book> node to the <bookstore> node:Xmldocument xmldoc = new xmldocument ();
Xmldoc. Load ("Bookstore. xml"); xmlnode root = xmldoc. selectsinglenode ("Bookstore"); // query <bookstore>
Xmlelement xe1 = xmldoc. createelement ("book"); // create a <book> node
Xe1.setattribute ("genre", "lizan red"); // you can specify the genre attribute of the node.
Xe1.setattribute ("ISBN", "2-3631-4"); // set the ISBN attribute of the node xmlelement xesub1 = xmldoc. createelement ("title ");
Xesub1.innertext = "Cs from entry to entry"; // set a text node
Xe1.appendchild (xesub1); // Add it to the <book> node
Xmlelement xesub2 = xmldoc. createelement ("author ");
Xesub2.innertext = "Hou Jie ";
Xe1.appendchild (xesub2 );
Xmlelement xesub3 = xmldoc. createelement ("price ");
Xesub3.innertext = "58.3 ";
Xe1.appendchild (xesub3); root. appendchild (xe1); // Add it to the <bookstore> node
Xmldoc. save ("Bookstore. XML "); // ================================================ ========= the result is: <? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book genre = "Li zanhong" ISBN = "2-3631-4">
<Title> Cs from entry to entry </title>
<Author> Hou Jie </author>
<Price> 58.3 </price>
</Book>
</Bookstore> 2. Modify the node: Change the genre value of the node whose genre attribute value is "Li zenhong" to "Update Li zenhong ", modify the text of the child node <author> of the node to "Yasheng ".Xmlnodelist nodelist = xmldoc. selectsinglenode ("Bookstore"). childnodes; // obtain all the subnodes of the bookstore Node
Foreach (xmlnode Xn in nodelist) // traverses all subnodes
{
Xmlelement Xe = (xmlelement) xn; // converts the subnode type to the xmlelement type
If (Xe. getattribute ("genre") = "") // If the genre attribute value is ""
{
Xe. setattribute ("genre", "Update lizan red"); // modify this attribute to "Update lizan red" xmlnodelist NLS = Xe. childnodes; // continue to obtain all the child nodes of the Xe subnode
Foreach (xmlnode xn1 in NLS) // traverse
{
Xmlelement xe2 = (xmlelement) xn1; // Conversion Type
If (xe2.name = "author") // If you find
{
Xe2.innertext = "Yasheng"; // modify
Break; // find and exit.
}
}
Break;
}
} Xmldoc. Save ("Bookstore. xml"); // save. // ================================================ ============= The final result is: <? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book genre = "Update Li zanhong" ISBN = "2-3631-4">
<Title> Cs from entry to entry </title>
<Author> Yasheng </author>
<Price> 58.3 </price>
</Book>
</Bookstore> 3. Delete the genre attribute of the <book genre = "Fantasy" ISBN = "2-3631-4"> node, delete the <book genre = "Update lizan red" ISBN = "2-3631-4"> node.Xmlnodelist xnl = xmldoc. selectsinglenode ("Bookstore"). childnodes; foreach (xmlnode Xn in xnl)
{
Xmlelement Xe = (xmlelement) xn;
If (Xe. getattribute ("genre") = "Fantasy ")
{
Xe. removeattribute ("genre"); // Delete genre attributes
}
Else if (Xe. getattribute ("genre") = "Update lizanhong ")
{
Xe. removeall (); // delete all content of the node
}
}
Xmldoc. save ("Bookstore. XML "); // ================================================ =====
The final result is: <? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book>
</Book>
</Bookstore> 4. display all data.Xmlnode xn = xmldoc. selectsinglenode ("Bookstore"); xmlnodelist xnl = xn. childnodes;

Foreach (xmlnode xnf in xnl)
{
Xmlelement Xe = (xmlelement) xnf;
Console. writeline (Xe. getattribute ("genre"); // display attribute values
Console. writeline (Xe. getattribute ("ISBN"); xmlnodelist xnf1 = Xe. childnodes;
Foreach (xmlnode xn2 in xnf1)
{
Console. writeline (xn2.innertext); // displays the child node text.
}
} Added content in 20172010.09.19 <? XML version = "1.0" encoding = "UTF-8"?>
<D3dversion>
<Version_display> 1 </version_display>
</D3dversion> read an XML file // version XML
String strlocdir = system. appdomain. currentdomain. basedirectory;
String strversion = "Sony 2D/3D converter software" + "/R/N" + "MPES-2D3D1 ";
Strversion + = "/R/N ";
Strversion + = "/R/N ";
Strversion + = "version: 1.00 ";

String verxmlpath = strlocdir + "2d3dversion. xml ";
String strrc1flag = "0"; xmldocument xmldoc = new xmldocument ();
Xmldoc. Load (verxmlpath); xmlnode xn = xmldoc. selectsinglenode ("d3dversion"); xmlnodelist xnl = xn. childnodes; foreach (xmlnode xnf in xnl)
{
Xmlelement Xe = (xmlelement) xnf;
// Console. writeline (Xe. getattribute ("version_display"); // display attribute values
Xmlnodelist xnf1 = Xe. childnodes;
Foreach (xmlnode xn2 in xnf1)
{
Strrc1flag = xn2.innertext;
}
} Write a file // verxml into your desired folder
String verxmlpath = strlocdir + "2d3dversion. xml"; xmltextwriter textwriter = new xmltextwriter (verxmlpath, encoding. utf8 );
Textwriter. Formatting = formatting. indented; // start the write process and call the writestartdocument method.
Textwriter. writestartdocument (); // write description
// Textwriter. writecomment ("first comment xmltextwriter sample example ");
// Textwriter. writecomment ("w3sky. XML in root dir"); // create a node
Textwriter. writestartelement ("2d3dversion ");
Textwriter. writeelementstring ("version_display", "0 ");
Textwriter. writeendelement (); // The end of writing a document. Call the writeenddocument method.
Textwriter. writeenddocument (); // disable textwriter
Textwriter. close (); ========================================================== ========================================================== = serialization method, read and Write XML files <? XML version = "1.0" encoding = "UTF-8"?>
<Ksbmconfig xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema">
<Connectstring> connectstring1 </connectstring>
<Serverpath> serverpath1 </serverpath>
<Smtpserver> smtpserver1 </smtpserver>
</Ksbmconfig> Create a class that contains the XML data structure: Public class ksbmconfig <br/>{< br/> /// <summary> <br/> /// </Summary> <br/> public ksbmconfig () <br/>{< br/>}</P> <p> private string _ connectstring; <br/> /// <summary> <br/> // connectstring. <br/> // </Summary> <br/> Public String connectstring <br/>{< br/> get {return _ connectstring ;} <br/> set {_ connectstring = value ;}< br/>}</P> <p> private string _ serverpath; <br/> /// <summary> <br/> // serverpath. <br/> // </Summary> <br/> Public String serverpath <br/>{< br/> get {return _ serverpath ;} <br/> set {_ serverpath = value ;}< br/>}</P> <p> private string _ smtpserver; <br/> // <summary> <br/> // SMTP. <br/> // </Summary> <br/> Public String smtpserver <br/> {<br/> get {return _ smtpserver ;} <br/> set {_ smtpserver = value ;} <br/>}< br/> /// <summary> <br/> // initial stage <br/> /// </Summary> <br/> Public void Init () <br/>{< br/> _ connectstring = ""; <br/> _ serverpath = ""; <br/> _ smtpserver = ""; <br/>}< br/>}When the button is pressed, read and write the XML file (note the package to be introduced) Private void button#click (Object sender, eventargs e) <br/>{< br/> string apath = system. io. path. getdirectoryname (system. reflection. assembly. getexecutingassembly (). location); <br/> apath = system. io. path. combine (apath, "1.xml"); </P> <p> // read <br/> ksbmconfig setting = loadfromxml (apath); </P> <p> setting. connectstring = "connectstring123"; <br/> setting. serverpath = "serverpath123"; <br/> setting. sm Tpserver = "smtpserver123"; </P> <p> // write <br/> bool B = savetoxml (apath, typeof (ksbmconfig), setting ); <br/>}</P> <p> Public static ksbmconfig loadfromxml (string filename) <br/>{< br/> ksbmconfig asetting = NULL; <br/> system. io. filestream FS = NULL; </P> <p> try <br/>{< br/> system. XML. serialization. xmlserializer serializer <br/> = new system. XML. serialization. xmlserializer (typeof (ksbmconfig); <br /> FS = new system. io. filestream (filename, system. io. filemode. open); <br/> asetting = (ksbmconfig) serializer. deserialize (FS); <br/>}< br/> catch (system. exception ex) <br/>{< br/> console. writeline (ex. tostring (); <br/>}< br/> finally <br/>{< br/> If (FS! = NULL) <br/>{< br/> FS. close (); <br/>}</P> <p> return asetting; <br/>}</P> <p> Public static bool savetoxml (string filename, system. type type, object target) <br/>{< br/> system. XML. serialization. xmlserializer serializer = NULL; <br/> system. io. streamwriter writer = NULL; <br/> bool issaved = false; </P> <p> try <br/>{< br/> writer = new system. io. streamwriter (filename, false); <br/> Seri Alizer = new system. XML. serialization. xmlserializer (type); <br/> serializer. serialize (writer, target); <br/> issaved = true; <br/>}< br/> catch (system. exception ex) <br/>{< br/> console. writeline (ex. tostring (); <br/>}< br/> finally <br/>{< br/> If (writer! = NULL) <br/>{< br/> writer. close (); <br/>}</P> <p> return issaved; <br/>}< br/>

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.