search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Home Backend Development XML/RSS Tutorial A simple way to write XML in .NET

A simple way to write XML in .NET

Mar 01, 2017 pm 04:59 PM
.net xml

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 <![CDATA[...]]> 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: <?name text?>

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(&quot;titles.xml&quot;, null);
     //写入根元素
     writer.WriteStartElement(&quot;items&quot;);
     //加入子元素
     writer.WriteElementString(&quot;title&quot;, &quot;Unreal Tournament 2003&quot;);
     writer.WriteElementString(&quot;title&quot;, &quot;C&amp;C: Renegade&quot;);
     writer.WriteElementString(&quot;title&quot;, &quot;Dr. Seuss&#39;s ABC&quot;);
     //关闭根元素,并书写结束标签
     writer.WriteEndElement();
     //将XML写入文件并且关闭XmlTextWriter
     writer.Close();  
  }
}

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

&lt;items&gt;
    &lt;title&gt;Unreal Tournament 2003&lt;/title&gt;
    &lt;title&gt;C&amp;amp;C: Renegade&lt;/title&gt;
    &lt;title&gt;Dr. Seuss&#39;s ABC&lt;/title&gt;
&lt;/items&gt;

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(&quot;myMedia.xml&quot;, null);
     //使用自动缩进便于阅读
     writer.Formatting = Formatting.Indented;
     //书写根元素
     writer.WriteStartElement(&quot;items&quot;);
     //开始一个元素
     writer.WriteStartElement(&quot;item&quot;);
     //向先前创建的元素中添加一个属性
     writer.WriteAttributeString(&quot;rating&quot;, &quot;R&quot;);
     //添加子元素
     writer.WriteElementString(&quot;title&quot;, &quot;The Matrix&quot;);
     writer.WriteElementString(&quot;format&quot;, &quot;DVD&quot;);
     //关闭item元素
     writer.WriteEndElement();  // 关闭元素
     //在节点间添加一些空格
     writer.WriteWhitespace(&quot;\n&quot;);
     //使用原始字符串书写第二个元素
     writer.WriteRaw(&quot;&lt;item&gt;&quot; + 
                     &quot;&lt;title&gt;BloodWake&lt;/title&gt;&quot; +
                     &quot;&lt;format&gt;XBox&lt;/format&gt;&quot; + 
                     &quot;&lt;/item&gt;&quot;);
     //使用格式化的字符串书写第三个元素
     writer.WriteRaw(&quot;\n  &lt;item&gt;\n&quot; +
                     &quot;    &lt;title&gt;Unreal Tournament 2003&lt;/title&gt;\n&quot; +
                     &quot;    &lt;format&gt;CD&lt;/format&gt;\n&quot; + 
                     &quot;  &lt;/item&gt;\n&quot;);
     // 关闭根元素
     writer.WriteFullEndElement();
     //将XML写入文件并关闭writer
     writer.Close();
  }
}

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

&lt;item rating=&quot;R&quot;&gt;
    &lt;title&gt;The Matrix&lt;/title&gt;
    &lt;format&gt;DVD&lt;/format&gt;
  &lt;/item&gt;
&lt;item&gt;
    &lt;title&gt;BloodWake&lt;/title&gt;
    &lt;format&gt;XBox&lt;/format&gt;
&lt;/item&gt;
  &lt;item&gt;
    &lt;title&gt;Unreal Tournament 2003&lt;/title&gt;
    &lt;format&gt;CD&lt;/format&gt;
  &lt;/item&gt;
&lt;/items&gt;

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 (m.sbmmt.com)!


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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to apply for signed works in Jinjiang Literature City_Jinjiang Literature City Signing Application Conditions [Advanced Guide] How to apply for signed works in Jinjiang Literature City_Jinjiang Literature City Signing Application Conditions [Advanced Guide] Jan 09, 2026 pm 08:03 PM

To sign a contract with Jinjiang Literature City, you must first complete real-name registration and publish three chapters of 10,000 words, and then submit an application containing a 286-290-word outline and other materials through the PC or APP, and must meet four hard conditions of word count, originality, real name, and material consistency.

Where to log in to the Chinese version of FanFiction software? 2025 latest APP Chinese version entrance Where to log in to the Chinese version of FanFiction software? 2025 latest APP Chinese version entrance Jan 10, 2026 am 06:51 AM

The Chinese version of FanFiction software does not require a separate login, you can directly access the official website https://www.fanfiction.net/ to use it; the 2025 Chinese version supports functions such as automatic system language adaptation, pure Chinese mode switching, real-time text translation, and intelligent language recognition.

How to adjust fmhy official website to Chinese How to adjust fmhy to Chinese How to adjust fmhy official website to Chinese How to adjust fmhy to Chinese Jan 21, 2026 am 08:42 AM

The default English interface of the FMHY official website can be switched to Chinese through five methods: 1. Enable the built-in translation in the browser; 2. Modify the browser language setting priority; 3. Install a third-party translation extension; 4. Use the webpage embedded translation toolbar; 5. Refer to the Chinese community documentation and mirroring instructions page.

How to view the list of installed optional features in Win11_Win11 opens the entrance to WSL, Hyper-V and other components [Development] How to view the list of installed optional features in Win11_Win11 opens the entrance to WSL, Hyper-V and other components [Development] Jan 10, 2026 pm 01:42 PM

You can view the enabled optional features of Windows 11 through four methods: Settings, Control Panel, PowerShell and DISM: 1. Installed features are displayed in Settings → Application → Optional Features; 2. The "Windows Features" window of the Control Panel displays the switch status of underlying components such as Hyper-V; 3. PowerShell executes the Get-WindowsOptionalFeature command to filter the Enabled items; 4. The DISM command dism/online/Get-Capabilities lists the full name of the functions whose State is Installed.

Annual work report ppt template Annual work report ppt template website recommendation Annual work report ppt template Annual work report ppt template website recommendation Jan 14, 2026 pm 07:36 PM

There are five ways to obtain annual work report PPT templates: 1. Free download of multi-industry templates from the first PPT platform; 2. PPTSTORE provides high-quality commercial templates; 3. SlideGenie uses AI to generate customized first drafts; 4. OfficePLUS Microsoft official enterprise-level templates; 5. Education PPT network, medical PPT and other vertical industry communities.

Blue Ocean Bookstore browser directly enters - Blue Ocean Bookstore does not need to download the web version Blue Ocean Bookstore browser directly enters - Blue Ocean Bookstore does not need to download the web version Jan 20, 2026 am 11:22 AM

There is no need to download the web version of Lanhai Sea Bookstore, just visit https://www.lanhaisea.net to use it; it has wide resource coverage, diverse themes, smooth operation, customizable interface, and supports bookshelf management and cross-end progress synchronization.

Free access to Pixiv works Free access to Pixiv works Jan 20, 2026 am 06:15 AM

The entrance to Pixiv's free works is https://www.pixiv.net, which supports high-definition original image browsing, GIF/WEBM animation playback, viewing of tags and creation instructions, thumbnail browsing for non-logged-in users, and low-definition preview downloads; homepage recommendations, top-three rankings, combined searches, and newbie areas to optimize content discovery; like protection, author reply highlighting, multi-level favorites, and follow dynamic push to enhance community interaction; contribution templates, privacy settings, timeline homepage, and novel annotation functions improve creative support.

C# XML document comment generation method C# how to automatically generate API documentation C# XML document comment generation method C# how to automatically generate API documentation Feb 05, 2026 am 07:57 AM

C# XML comments must start with /// and be immediately above the declaration, with tags such as and and true, and enable true in .csproj to generate XML document files.

Related articles