C # Xmlreader/xmlwriter Class

Source: Internet
Author: User
Tags flushes processing instruction

XmlReader is used to read XML files, and XmlWriter is used to write data to an XML file. In fact, in the impression that many of the XML operation classes support direct save, read also supports the acceptance of XmlReader and XmlWriter class examples as parameters, but why also have this two classes specifically for reading and writing XML files? Because they have a powerful custom format function;

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:

    classProgram {Static voidMain (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 BeiConsole.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 voidMain (string[] args) {            //<?xml version= "1.0" encoding= "Utf-8"?>//<Persons>//<Person>//<!--It's a cow ---//<Name> Liu Bei </Name>//<Age>28</Age>//</Person>//</Persons>xmlreadersettings rsetting=Newxmlreadersettings (); Rsetting.ignorecomments=false;//if set to true, all comments are ignoredXmlReader Reader= Xmlreader.create (@"D:\123.xml", rsetting); Reader.            ReadString ();  while(reader. Read ()) {if(Reader. NodeType = =xmlnodetype.comment) {Console.WriteLine (reader).    Value); //this is a cow.}} 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 voidMain (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 =NewFileStream (@"D:\123.xml", Filemode.create,fileaccess.write)) {                using(XmlWriter XW =xmlwriter.create (FS)) {                    //XML DeclarationXw. WriteStartDocument (true); Xw. WriteStartElement ("Persons"); Xw. WriteStartElement (" Person"); Xw. WriteStartElement ("Name"); Xw. WriteString ("Liu Bei"); Xw.                    WriteEndElement (); Xw. WriteStartElement (" Age"); Xw. WriteValue ( -); 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 voidMain (string[] args) {            //<Persons>//<Person>//<Name> Liu Bei </Name>//<Age>28</Age>//</Person>//</Persons>xmlwritersettings wsetting=Newxmlwritersettings (); //Remove XML declarationWsetting.omitxmldeclaration =true; Wsetting.indent=true; using(FileStream fs =NewFileStream (@"D:\123.xml", Filemode.create,fileaccess.write)) {                using(XmlWriter XW =xmlwriter.create (FS, wsetting)) {                    //XML DeclarationXw. WriteStartElement ("Persons"); Xw. WriteStartElement (" Person"); Xw. WriteStartElement ("Name"); Xw. WriteString ("Liu Bei"); Xw.                    WriteEndElement (); Xw. WriteStartElement (" Age"); Xw. WriteValue ( -); 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.

C # Xmlreader/xmlwriter Class

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.