Writing XML in Visual C # using XML

Source: Internet
Author: User
Tags cdata constructor contains sleep
Visual|xml in my last article, "C #, using xml--to read XML," and discussed how to use the classes provided in the. NET framework to read XML in C # and some related concepts of reading, so let's talk today about how to write XML documents in C #. At first I thought it was a bit of a trouble to write XML programmatically, and then I thought it would be useful, and I think the Microsoft guys could have made these classes just to get the Bill Gates to work! As for its usefulness ... For example, to do installation program Ah! We can generate the corresponding XML document based on the options that the user chooses during the installation process and some settings to initialize our application based on the XML document. Empty words do not say so much, let's take a look at the specific implementation details.

To write XML is also the concept of streaming, the details of writing XML in. NET are implemented as XmlWriter classes, but the class is not instantiated by an abstract class, so we want to access its methods in the program to implement the desire to write XML, It is necessary to use its derived class XmlTextWriter, which provides a series of properties and methods to prepare us for writing XML, which is described in detail below:

constructor function:

Public XmlTextWriter (TextWriter);
Public XmlTextWriter (Stream, Encoding);
Public XmlTextWriter (string, Encoding);
The first constructor passes the existing TextWriter instance, and the System.IO.TextWriter class is an ordered character stream

The second constructor takes the stream to be written as the first argument, the second parameter is the encoding of the specified XML document, the default is UTF8, the encoding enumeration value, the stream can be filestream,memorystream,networkstream, and so on

The third constructor passes the file name you want to write as a string (overriding the file if it exists) to the first argument, and the second parameter specifies how the encoding

Common methods:

Writerstartdocument () and Writerenddocument () methods:

The first method is used to write the XML declaration section, such as: <?xml version= "1.0" encoding= "UTF-8"?

The second method is used to close any open elements or attributes and reset the writer to the start state.

Writerstartelement () and WriteEndElement () methods:

The first method is used to write out the specified start tag, which has the following overloads:

Writerstartelement (String localname)
Use the passed string as the local name of the element

Writerstartelement (string localname,string namespace)
The first parameter specifies the local name of the element, and the second parameter specifies the namespace in which the element is located

Writerstartelement (String prefix,string localname,string namespace)
The first parameter specifies the prefix of the element, the second parameter specifies the local name of the element, and the third parameter specifies the namespace in which the element is located

The second method is used to write off the closing element that corresponds to the start element, and if the starting element contains nothing, a "/>" is used as the closing element

Writerstartattribute () and Writerendattribute () methods:

The first method is used to write the beginning of a property that has two overloads:

Writerstartattribute (string localname,string namespace)
The first parameter specifies the local name of the property, and the second parameter specifies the namespace in which the property is located

Writerstartattribute (String prefix,string localname,string namespace)
The first parameter specifies the prefix of the property, the second parameter specifies the local name of the property, and the third argument specifies the namespace in which the property is located

The second method is used to turn off the properties created by Writerstartattribute

Writerelementstring () Method:

The method can create an element that contains a string value that has the following overloads:

Writerelementstring (string localname,string value)
If you write this code: writerelementstring ("Para", "Some text") will output: <para> Some text </para>

Writerelementstring (String localname,string namespace,string value)
If you write this code: writerelementstring ("Para", "Http://www.w3.org/ns", "Some text") will output: <para xmlns= "Http://www.w3.org/ns" >some text </para>

If you write elements that are nested in a few levels, you can use the Writerstartelement () and Writerendelement () methods if you write elements that directly contain content

Writerattributestring () Method:

Similar to the writerelementstring () method used to write a property directly if the value of the property does not contain an entity, if the property value contains an entity that can use Writerstartattribute () and Writerendattribute () method, such as to write out such a Xml--<para author= "Do&0241;a&l.perez"/>, you can write the following code:

Writerstartelement ("Para");
Writerstartattribute ("author", null);
Writerstring ("Do");
Writercharentiry ("~n");
Writerstring ("a");
Writercharentiry ("&");
Writerstring ("L.perez");
Writerendattribute ();
Writerendelement ();
The method has the following overloads:

Writerattributestring (string localname,string value);
Writerattributestring (String localname,string namespace,string value);
Writerattributestring (String Prefx, String localname,string namespace,string value);
Writernode (XmlReader Reader,bool defattr) method:

The method can copy nodes from the XmlReader reader and write them to the XmlWriter stream, the first parameter is an instance of XmlReader, and the second parameter accepts a Boolean value to decide whether to copy the attributes in the element, taking into account the following XML fragment:

<para>
<sent>
The <b> XmlWriter </b> class writes XML content to a Stream.
</sent>
</para>
The following code copies the fragment in which the reader represents an instance of XmlReader writer representing an instance of the XmlWriter class:

while (reader. Read ())
{
if (reader. Name = = "Sent" && reader. NodeType = = XmlNodeType.Element)
{
Writer. Writernode (reader,true);
}
}
Get the following output:

<sent>

The <b> XmlWriter </b> class writes XML content to a Stream.

</sent>

Writercomment (String text) method: used to write comments

Writerstring (String text) method: used to write text

Writercdata (String text) method: Writes out a CDATA block of data

WriterBase64 (byte[] buffer,int index,int count) method: Encodes the specified binary byte as Base64 and writes out the resulting text

Flush (): Flushes all content in the buffer to the underlying stream and simultaneously refreshes the underlying stream close (): Closes this stream and the underlying stream

The above is a brief introduction to some important methods of the XmlTextWriter class, so let's take a look at a routine to see how to use these methods in a program.

The Example1 button writes out the XML declaration and an element node as well as the text within the node, and the Example2 button adds the attribute node, nested elements and text to the Example1, WriteNode button to use Writernode () method to copy all the elements and attributes in the reader in an existing reader and write to a new XML document. The Example3 button will write a complete XML document, EXAMPLE4 Press button to build a separate document on the Example3 button and append a CDATA section to the document. The Example5 button encodes a picture and writes the encoded data to an XML document using the WriterBase64 () method. The Example6 button uses the XML generated in the Example5 button to read the data and decode the encoded data to produce a picture.

Here is the functional implementation code:

The following is the XML file to use in the WriteNode button:

Tang poetry. Xml

<?xml version= "1.0" encoding= "gb2312"?
Tang poetry
The five words and the rhyme
Author's font size = "Taibai" > Li Bai </author
Title > static night thinking </title >
The contents of the bed before the moonlight, doubt is on the ground frost. Looking up at the moon, head to think of home. </Content >
</Five words and rhyme
The five words and the rhyme
Author's font size = "Taibai" > Litaibai </author
Title > Spring </Title >
Content > Spring sleep don't feel xiao, everywhere smell bird. Night to wind and rain sound, flowers fall to know how much. </Content >
</Five words and rhyme
The five words and the rhyme
Author's font size = "Tiling" > Wang Zhihuan </author
Title > The Yellow River enters the current. Want to be poor and </content
</Five words and rhyme
The five words and the rhyme
Author > </author of Li Qingzhao
Title > Dream Order </Title
Content > Last night wind sparse rain suddenly, thick sleep does not eliminate residual wine, test questionnaire curtain person, but the way Begonia still, know no, know, should be flourishing leaves. </Content >
</Five words and rhyme
</Tang Poetry

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.