C # Simple XML read-Modify Write

Source: Internet
Author: User
Tags cdata xsl

XML Concepts
Root XML root node, only and must have one (above for linklibrary)
element node elements (such as link)
Attribute node attributes (such as Cat, Url, Desc)
Content contents (non-blank text, CDATA, Element, EndElement, EntityReference, or endentity) nodes

System.Xml Space
The following classes are suitable for fast streaming read and write XML files (Note: DOM is suitable for random reads and writes)
XmlReader, XmlWriter,
XmlTextReader, XmlTextWriter
XmlValidatingReader, Xmlvalidatingwriter adds DTD and schema validation, thus providing validation of data
XmlNodeReader, XmlNodeWriter the XmlNode as its source.

Node type (public enum XmlNodeType)
XmlDeclaration XML declarations (for example, <?xml version= "1.0"?>).
Attribute attributes (for example, id= "123").
CDATA CDATA Sections (for example, <! [Cdata[my escaped text]]>).
Comment annotations (for example,,<!--my Comment-->)
Document provides access to the entire XML document as the root of the document tree.
DocumentFragment the document fragment.
DocumentType the document type declaration indicated by the following markup (for example, <! doctype...>).
Element elements (for example,,<item>).
EndElement the end element tag (for example,,</item>).
Entity entity declarations (for example, <! entity...>).
Endentity returns when the XmlReader arrives at the end of an entity substitution because of a call to ResolveEntity.
EntityReference entity references (for example,,&num;).
None if the Read method is not called, it is returned by XmlReader.
Notation the notation in a document type declaration (for example, <! notation...>).
ProcessingInstruction processing instructions (for example, <?pi test?>).
SignificantWhitespace white space between tags in a mixed content model or a xml:space= "preserve" range.
The textual content of the text node.
White space between the whitespace tags.


------------------------------------------------------------------------
Using XmlTextWriter to write quickly
------------------------------------------------------------------------
Closing
XmlTextWriter writer = new XmlTextWriter (@ "C:/mywriter.xml", null);
Writer. Close ();

Starting and ending XML document (<?xml version= "1.0"?>
Writer. WriteStartDocument ();
Writer. Enddocument ();

declaring XML Formats
Writer. formatting = formatting.indented;
Writer. Indentation = number of characters indented
Writer. IndentChar = indent character
Writer. QuoteChar = Single quotation mark | double quotation mark

Output comment (<!--comment text-->)
Writer. WriteComment ("comment text");

Output elements (<Element>ElementVal</Element>)
Writer. WriteElementString ("Element", "Elementval");
Or
Writer. Startelement ("Element");
Writer. WriteString ("Elementval");
Writer. EndElement ();

Output element properties (<element property= "Propertyval" >ElementVal</Element>)
Writer. Startelement ("Element");
Writer. WriteAttributeString ("Property", "Propertyval");
Writer. WriteString ("Elementval");
Writer. EndElement ();

Output CDATA (<! Cdata>....</cdata>
Writecdata ("...")

Output character Buffer text
WriteChars (char[], startpos, length)

An XML file (Bookstore.xml) is known 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 into the <bookstore> node:

XmlDocument xmldoc=new XmlDocument ();
Xmldoc.load ("Bookstore.xml");
XmlNode Root=xmldoc.selectsinglenode ("bookstore");//Find <bookstore>
XmlElement xe1=xmldoc.createelement ("book");//Create a <book> node
Xe1. SetAttribute ("Genre", "Li Zhanhong");/set the node genre property
Xe1. SetAttribute ("ISBN", "2-3631-4");//Set the node ISBN property

XmlElement xesub1=xmldoc.createelement ("title");
Xesub1. Innertext= "CS from getting started to proficient";/Set Text node
Xe1. AppendChild (XESUB1);//Add to <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 to <bookstore> node
Xmldoc.save ("Bookstore.xml");


//================
The results are:

<?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 Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> Hou Jie </author>
<price>58.3</price>
</book>
</bookstore>


2, modify the node: The genre property value of "Li Zhanhong" node genre value changed to "Update Li Zhanhong", the node's child node <author> text modified to "Asia wins."

XmlNodeList Nodelist=xmldoc.selectsinglenode ("bookstore"). childnodes;//gets all the child nodes of the bookstore node
foreach (XmlNode xn in nodelist)//traverse all child nodes
{
XmlElement xe= (XmlElement) xn;//Converts a child node type to a XmlElement type
if (XE. GetAttribute ("genre") = = "Li Zhanhong")//If genre property value is "Li Zhanhong"
{
Xe. SetAttribute ("Genre", "Update Li Zhanhong");//Modify this property to "Update Li Zhanhong"

XmlNodeList Nls=xe. CHILDNODES;//continues to fetch all child nodes of the XE child node
foreach (XmlNode xn1 in NLS)//traversal
{
XmlElement xe2= (XmlElement) xn1;//conversion type
if (Xe2. name== "Author")//If found
{
Xe2. innertext= "Asia wins";//Modify
break;//find out and get out of here.
}
}
Break
}
}

Xmldoc.save ("Bookstore.xml"),//save.



//=================

The final results are:

<?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 Zhanhong" isbn= "2-3631-4" >
<title>cs from getting started to mastering </title>
<author> Asia wins </author>
<price>58.3</price>
</book>
</bookstore>



3, delete <book genre= "Fantasy" isbn= "2-3631-4" > Node genre properties, delete <book genre= "update Li Zhanhong" 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 property
}
else if (XE. GetAttribute ("genre") = = "Update Li Zhanhong")
{
Xe. RemoveAll ()//delete all contents of the node
}
}
Xmldoc.save ("Bookstore.xml");

//====================

The final results are:

<?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 the 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 property value
Console.WriteLine (XE. GetAttribute ("ISBN"));

XmlNodeList Xnf1=xe. ChildNodes;
foreach (XmlNode xn2 in Xnf1)
{
Console.WriteLine (xn2. innertext);//Display child node point text
}
}

------------------------------------------------------------------------
Write routines
------------------------------------------------------------------------
[C-sharp] View Plain copy print? xmltextwriter writer = new xmltextwriter  (filename, null);  //Use  indenting for readability.   writer. formatting = formatting.indented;  //xml Statement (write the xml delcaration.  )    writer. WriteStartDocument ();  //preprocessing instructions (write the processinginstruction node.)    string pitext= "type=" text/xsl " href=" book.xsl "";   writer. WriteProcessingInstruction ("Xml-stylesheet",  pitext);  //Document type (Write the documenttype  node.)    writer. Writedoctype ("book", null , null,  "<!") entity h  "Hardcover" > ");  //Notes (Write a comment node.)    writer. WriteComment ("Sample xml");  //root element (write a root element.)    writer. WriteStartElement ("book");  //property value (Write the geNre attribute.)    writer. WriteAttributeString ("Genre",  "novel");  //property value (Write the isbn attribute.)     writer. WriteAttributeString ("ISBN",  "1-8630-014");  //write the title.   writer. WriteElementString ("title",  "The handmaid" S tale ");  //write the style  element.   writer. WriteStartElement ("style");   writer. Writeentityref ("H");   writer. WriteEndElement ();   //Text element node (write the price.)    writer. WriteElementString ("Price",  "19.95");  //[cdata]   writer. Writecdata ("prices 15% off!!");   //write the close tag for the root element.   Writer. WriteEndElement ();   writer. WriteEndDocument ();  //write the xml to file and close the  writer.   WRIter. Flush ();   writer. Close ();   //load the file into an xmldocument to ensure  well formed XML.   xmldocument doc = new xmldocument ();   //preserve white space for readability.   Doc. preservewhitespace = true;  //load the file.   Doc. Load (filename);   //display the xml content to the console.    Console.Write (Doc. INNERXML);   

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.