. NET Learning Notes---XML operations and read-write

Source: Internet
Author: User
Tags flushes net xml processing instruction

One, the corresponding class in. NET in the XML file operation

Microsoft's. The NET Framework provides a series of classes for the implementation of the DOM in the System.Xml namespace.

The following is a list of the components of the XML document that correspond to the classes in. NET:

XML Document Components Corresponds to a class in. net
Processing instructions XmlProcessingInstruction
Refers to ELEMENT nodes XmlElement
Property XmlAttribute
Text node XmlText
Node XmlNode
Document XmlDocument
Properties of the XmlWriter object XmlWriterSettings
Comments Xmlcomment
Second, the XML document various processing class

  1, XmlNode node class: Including element node, text node, attribute node and so on.

  This class can be said to be the foundation of. Net XML operations, and most XML operation classes inherit from this class. Many classes rewrite the methods of the class, and so on.

This class member properties, methods are many, but are very simple, nothing more than the addition of XML documents, modify, query, save and other operations. So, just by looking at MSDN is enough:

Xmlnode:http://msdn.microsoft.com/zh-cn/library/system.xml.xmlnode_members (v=vs.80). aspx

In addition, basically, all classes inherit from this class, all of which are similar.

  2, XmlElement inherits the XmlNode, refers to the element node.

Features of XmlElement:

    • XmlElement inherits from Xmllinkednode and inherits from XmlNode class.
    • XmlElement refers to element nodes , and XML nodes have several types: attribute nodes, annotation nodes, text nodes, element nodes, and so on. That is, XmlNode is the general term for these multiple nodes.
    • XmlElement is an active class that can be instantiated directly, whereas XmlNode is an abstract class that must be returned by some method of XmlDocument.

Here is just one of the simplest examples:

Sample XML Document:

<?xml version= "1.0" encoding= "gb2312"?><article> <author  age= "A" > Zhang San </author>  <length>12000</length>  <price>42</price></Article>

Simple example:

        static void Main (string[] args)        {            //xmldocument            XmlDocument doc = new XmlDocument ();            Doc. Load (@ "D:\Articles.xml");            XmlNode appearances            XmlNode node = doc. selectSingleNode ("article");            String author = node. Firstchild.innertext;            Console.WriteLine (author);  Output Zhang San            //xmlelement exit            XmlElement element = doc. documentelement;   The root element node            Console.WriteLine (element. Name);            XmlAttribute appearances            XmlAttribute attribute = element. Firstchild.attributes[0];  Output of            Console.WriteLine (attribute. Value);            Xmlcomment appearances            xmlcomment comment = doc. Createcomment ("This is the word count!");            Element. PrependChild (comment);            Doc. Save (@ "D:\123123.xml");            Console.readkey ();        }

First, the use of XmlReader

The XmlReader class is designed to read XML files, with the greatest feature of supporting settings.

Property Description
Attributecount When overridden in a derived class, gets the number of properties on the current node
BaseURI When overridden in a derived class, gets the base URI of the current node
Canreadbinarycontent Gets a value that indicates whether the XmlReader implements binary content read methods
Depth Gets the depth of the current node in the XML document
Eof Gets a value that indicates whether this reader is positioned at the end of the stream
HasAttributes Gets a value that indicates whether the current node has any properties
HasValue Gets a value that indicates whether the current node can have the value
IsDefault Gets a value that indicates whether the current node is an attribute generated from a default value defined in a DTD or schema
Isemptyelement Gets a value that indicates whether the current node is an empty element (for example, <MyElement/>)
Item Gets the value of the property with the specified index, supports shaping, strings, LocalName, and NamespaceURI as arguments
LocalName Gets the local name of the current node
Name Gets the qualified name of the current node
NamespaceURI Gets the namespace URI of the node on which the reader is positioned
NameTable Gets the XmlNameTable associated with the implementation
NodeType Gets the type of the current node
Prefix Gets the namespace prefix associated with the current node
QuoteChar Gets the quote character used to enclose the value of the attribute node
ReadState Get the state of the reader
SchemaInfo Gets the schema information that is assigned to the current node as a result of schema validation
Settings Gets the XmlReaderSettings object that is used to create this XmlReader instance
Value Gets the text value of the current node
ValueType Gets the common language runtime (CLR) type of the current node
Xmllang Get the current Xml:lang range
XmlSpace Get the current Xml:space range

Common methods:

Method Description
Close Change ReadState to Closed
Create Creates a new XmlReader instance with the specified parameter type
Dispose Frees all resources occupied by the current instance of the XmlReader class
GetAttribute When overridden in a derived class, gets the value of the property with the specified index
Getvalueasync Asynchronously gets the value of the current node
Isname Returns a value that indicates whether the string argument is a valid XML name
Isnametoken Returns a value that indicates whether the string argument is a valid XML name tag
Isstartelement Call MoveToContent and test whether the current content node is a start tag or an empty element tag
LookupNamespace Resolves namespace prefixes within the scope of the current element
MoveToAttribute Move to a property with the specified index
MoveToContent

If this node is not a content node, the reader jumps forward to the next content node or end of the file.
It skips the following types of nodes: ProcessingInstruction, DocumentType, Comment, whitespace, or significantwhitespace

Movetoelement Move to the element that contains the current attribute node
MoveToFirstAttribute Move to the first property
MoveToNextAttribute Move to Next property
Read Reads the next node from the stream
Readattributevalue Resolves a property value to one or more Text, EntityReference, or endentity nodes
ReadContentAs Reads the content as an object of the specified type
Readstartelement Checks whether the current node is an element and advances the reader to the next node
ReadElementContentAs Reads the element content as a request type
Readelementstring Reading plain text elements
Readendelement Checks whether the current content node is an end tag and advances the reader to the next node
ReadInnerXml Read all content (including tags) as a string
ReadOuterXml Reads the contents (including tags) that represent the node and all its children
ReadString Reads the contents of an element or text node as a string
ReadSubtree This instance can be used to read the current node and all its child nodes
Readtodescendant Let XmlReader advance to the next descendant element with the specified qualified name
Readtofollowing Read until the element with the specified qualified name is found
ReadToNextSibling Let XmlReader advance to the next sibling element with the specified qualified name
ReadValueChunk Read a large number of text streams embedded in an XML document
ResolveEntity Resolving entity references for EntityReference nodes
Skip Skips the children of the current node

Example:

    Class program    {        static void Main (string[] args)        {            //<?xml version= "1.0" encoding= "Utf-8"?>            //<persons>            //  <Person>            //    <Name> Liu Bei </Name>            //    <age >28</Age>            //  </Person>            //</persons>            XmlReader reader = xmlreader.create ( @ "D:\123.xml");            Reader. ReadString ();            while (reader. Read ())            {                if (reader. NodeType = = XmlNodeType.Element)                {                    if (reader. name = = "Name")                    {                        Console.WriteLine (reader). Readelementstring ());  Liu Bei                        Console.WriteLine (reader). HasAttributes);    False                    }}}            console.readkey ();        }    }

Most methods and properties are used in a similar way to the above example, not verbose. Here, XmlReader features, custom formats, the most important of which is the attribute settings.

Example 2:

        static void Main (string[] args)        {            //<?xml version= "1.0" encoding= "Utf-8"?>//<persons>  <Person>            //    <!--This is a cow--/            /    <Name> Liu Bei </Name>            //    < Age>28</age>            //  </Person>            //</persons>            xmlreadersettings rsetting = new XmlReaderSettings ();            Rsetting.ignorecomments = false;    If set to true, all comments are ignored                        XmlReader reader = xmlreader.create (@ "D:\123.xml", rsetting);            Reader. ReadString ();            while (reader. Read ())            {                if (reader. NodeType = = xmlnodetype.comment)                {                    Console.WriteLine (reader). Value);    This is a bull man                }            }            Console.readkey ();        }    }

Second, the use of XmlWriter

Common Properties:

Property Description
Settings Gets the XmlWriterSettings object that is used to create this XmlWriter instance
WriteState When overridden in a derived class, gets the state of the writer
Xmllang When overridden in a derived class, gets the current Xml:lang range
XmlSpace When overridden in a derived class, gets the XmlSpace that represents the current Xml:space range

Common methods:

Method Description
Close When overridden in a derived class, closes this stream and the underlying stream
Create Creates a new XmlWriter instance with the specified stream
Dispose Frees all resources occupied by the current instance of the XmlWriter class
Flush Flushes all the contents of the buffer to the underlying stream and flushes the underlying stream at the same time
LookupPrefix Returns the nearest prefix defined for the namespace URI in the current namespace scope
WriteAttributes Writes out all properties found in the current position in the XmlReader
WriteAttributeString Writes out the property with the specified local name and value
WriteBase64 Encodes the specified binary byte into Base64 and writes out the resulting text
Writebinhex Encodes the specified binary byte into BinHex and writes out the resulting text
Writecdata Writes out the <! containing the specified text [cdata[...] > Blocks
WriteCharEntity Forces a character entity to be generated for the specified Unicode character value
WriteChars Writes text in one buffer at a time
WriteComment Write a comment that contains the specified text <!--...-->
Writedoctype Writes out the DOCTYPE declaration with the specified name and optional attributes
WriteElementString Writes an element with the specified local name and value
WriteEndAttribute Close the previous WriteStartAttribute call
WriteStartDocument Write an XML declaration with version "1.0"
WriteEndDocument Closes any open elements or attributes and sets the writer back to the Start state
Writestartelemen Writes the specified start tag and associates it with the given namespace and prefix
WriteEndElement Closes an element and pops the corresponding namespace range
Writeentityref Press &name; Write out entity references
Writefullendelement Closes an element and pops the corresponding namespace range
Writename Write the specified name to ensure it is compliant with the 1.0 recommendations
Writenmtoken Write the specified name to ensure it is compliant with the 1.0 recommendations
WriteNode Copy all content from the reader to the writer and move the reader to the next sibling
WriteProcessingInstruction Write a processing instruction with a space between the name and the text
Writequalifiedname Writes out the namespace-qualified name. This method finds a prefix that is within the scope of a given namespace
WriteRaw Manually writing raw markup from a string
WriteStartAttribute Writes the starting point of a property with the specified local name
WriteString Write the given text content
WriteSurrogateCharEntity Generate and write surrogate character entities for surrogate character pairs
WriteValue Writes a value of the type specified in a parameter
Writewhitespace Write a given blank

Example:

        static void Main (string[] args) {//<?xml version= "1.0" encoding= "Utf-8" standalone= "yes" ;<persons><person><name> Liu Bei </name><age>28</age></person></persons                > Using (FileStream fs = new FileStream (@ "D:\123.xml", Filemode.create,fileaccess.write)) { using (XmlWriter XW = XmlWriter.Create (fs)) {//xml declaration XW.                    WriteStartDocument (TRUE); Xw.                    WriteStartElement ("Persons"); Xw.                    WriteStartElement ("person"); Xw.                    WriteStartElement ("Name"); Xw.                    WriteString ("Liu Bei"); Xw.                    WriteEndElement (); Xw.                    WriteStartElement ("Age"); Xw.                    WriteValue (28); Xw.                    WriteEndElement (); Xw.                    WriteEndElement (); Xw.                    WriteEndElement (); Xw.                WriteEndDocument (); }           } console.readkey (); }

The above comment is the document generated by the code.

There are some problems with the XML generated above, no line breaks, no reading. And what if I want to get rid of the XML declaration?

Example 2:

        static void Main (string[] args) {//<persons>//<Person>// <Name> Liu Bei </Name>//<Age>28</Age>//</Person>//<            /persons> xmlwritersettings wsetting = new XmlWriterSettings ();            Remove XML declaration wsetting.omitxmldeclaration = true;            Wsetting.indent = true; using (FileStream fs = new FileStream (@ "D:\123.xml", Filemode.create,fileaccess.write)) {using ( XmlWriter XW = XmlWriter.Create (FS, wsetting)) {//xml declaration XW.                    WriteStartElement ("Persons"); Xw.                    WriteStartElement ("person"); Xw.                    WriteStartElement ("Name"); Xw.                    WriteString ("Liu Bei"); Xw.                    WriteEndElement (); Xw.                    WriteStartElement ("Age"); Xw.                    WriteValue (28); Xw. WriteendeLement (); Xw.                    WriteEndElement (); Xw.                WriteEndElement ();        }} console.readkey (); }

The resulting XML is indented and stripped of the namespace, and more settings are set in instances of the XmlWriterSettings class.

. NET Learning Notes---XML operations and read-write

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.