A simple way to write XML in .NET

黄舟
Release: 2017-03-01 16:59:44
Original
1380 people have browsed it

xml is a popular technology. One of the main reasons why it arouses people's interest is that it is very simple and people can easily understand and use it. Every programmer can easily read an XML file and understand the content it contains.

.NET contains many classes that support XML. These classes make programmers use XML programming as easy as understanding XML files. In this article, I will give an example of the use of such a class, which is the XmlTextWriter class.

The XmlTextWriter class allows you to write XML to a file. This class contains many methods and properties that make it easier for you to process XML. In order to use this class, you must first create a new XmlTextWriter object, and then you can add XML fragments to this object. This class contains many methods for adding various types of XML elements to XML files. The following table gives the names and descriptions of these methods:

Method
Description

WriteStartDocument
Write an XML declaration with version "1.0"

WriteEndDocument
Close any open element or attribute

Close
Close the stream

WriteDocType
Write a DOCTYPE declaration with the specified name and optional attributes

WriteStartElement
Write the specified start tag

WriteEndElement
Close an element

WriteFullEndElement
Close an element and always write the complete end tag

WriteElementString
Write an element containing a string value

WriteStartAttribute
Write attribute The starting content

WriteEndAttribute
Close the previous WriteStartAttribute call

WriteRaw
Manually write the original tag

WriteString
Write a string

WriteAttributeString
Out the attribute with the specified value

WriteCData
Write out the block containing the specified text

WriteComment
Write a comment containing the specified text

WriteWhiteSpace
Write out the given white space

WritePRocessingInstruction
Write out Processing instructions with spaces between the name and the text, as shown below:

If you are very familiar with XML, then you will be able to understand the above methods well. . Below we will give an example, in which we will first create a document, add some elements, and then close the document. After adding an element you can also add sub-elements, attributes and other content. The following code is an example of this, which creates an XML file named title.

using System;
using System.IO;
using System.Xml;
public class Sample
{
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("titles.xml", null);
     //写入根元素
     writer.WriteStartElement("items");
     //加入子元素
     writer.WriteElementString("title", "Unreal Tournament 2003");
     writer.WriteElementString("title", "C&C: Renegade");
     writer.WriteElementString("title", "Dr. Seuss's ABC");
     //关闭根元素,并书写结束标签
     writer.WriteEndElement();
     //将XML写入文件并且关闭XmlTextWriter
     writer.Close();  
  }
}
Copy after login

If you compile and execute the above code, you will create this XML file with the following content:

<items>
    <title>Unreal Tournament 2003</title>
    <title>C&amp;C: Renegade</title>
    <title>Dr. Seuss&#39;s ABC</title>
</items>
Copy after login

The above code creates an XmlTextWriter named writer object. When this object is created, it is associated with a file named titles.xml. Next, the program creates a root property called items, and the WriteStartElement method creates the start tag for this property. Next, the program calls the WriteElementString method to create three child elements. You can also see from the above code that this method uses the first parameter (title in the above program) as the element's label; it uses the second parameter as the element's value. After you have added all the elements, you need to close the root element. At this time you can call the WriteEndElement method to close the most recently opened element; in this case, the most recently opened element is the root element. When all the data has been written and the root element has been closed, you can pass the information to your XmlTextWriter. This means that you can call the Close method to close it at this time.

The above code is relatively simple. Let's look at an example that uses more methods in the XmlTextWriter class and has more complete functions.

using System;
using System.IO;
using System.Xml;
public class Sample
{
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("myMedia.xml", null);
     //使用自动缩进便于阅读
     writer.Formatting = Formatting.Indented;
     //书写根元素
     writer.WriteStartElement("items");
     //开始一个元素
     writer.WriteStartElement("item");
     //向先前创建的元素中添加一个属性
     writer.WriteAttributeString("rating", "R");
     //添加子元素
     writer.WriteElementString("title", "The Matrix");
     writer.WriteElementString("format", "DVD");
     //关闭item元素
     writer.WriteEndElement();  // 关闭元素
     //在节点间添加一些空格
     writer.WriteWhitespace("\n");
     //使用原始字符串书写第二个元素
     writer.WriteRaw("<item>" + 
                     "<title>BloodWake</title>" +
                     "<format>XBox</format>" + 
                     "</item>");
     //使用格式化的字符串书写第三个元素
     writer.WriteRaw("\n  <item>\n" +
                     "    <title>Unreal Tournament 2003</title>\n" +
                     "    <format>CD</format>\n" + 
                     "  </item>\n");
     // 关闭根元素
     writer.WriteFullEndElement();
     //将XML写入文件并关闭writer
     writer.Close();
  }
}
Copy after login

After compiling and running the above code, you will get the myMedia.xml file. The content of the file is:

<item rating="R">
    <title>The Matrix</title>
    <format>DVD</format>
  </item>
<item>
    <title>BloodWake</title>
    <format>XBox</format>
</item>
  <item>
    <title>Unreal Tournament 2003</title>
    <format>CD</format>
  </item>
</items>
Copy after login

The comments in the above code indicate that the function of this program is How to achieve it. One thing to remember is that when you call a method to start an operation, you need to call a method at the appropriate place in your program to end the operation. For example, if you call StartElement, you must call EndElement to close the element; of course, you can also add a child element between these two calls. Whenever you call the EndElement method, it always closes the element most recently opened using the StartElement method (this is very similar to how a stack works).

It is very easy to use XmlTextWriter, but I still recommend that you try these codes and methods yourself. Once you try it, you'll find that the code can be easily integrated into your program. You should also remember that XmlTextWriter is just one of many XML classes provided by .NET. Like XmlTextWriter, other XML classes are also very easy to use

The above is the content of a simple method of writing XML in .NET. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template