`

Writing XML with the XmlWriter class

    博客分类:
  • C#
 
阅读更多

In previous chapters we have dealt with reading XML, but now it's time to start writing it as well. Since XML is simply text, you could just start writing out XML tags to a file and give it an xml extension, but it's more easy and safer to let the .NET framework handle it, and just like with reading XML, there are at least two different options: The XmlWriter approach and the XmlDocument approach. This article will focus on the first approach, and then we'll look into writing XML with the XmlDocument in the next chapter.

The difference between the two is once again mostly related to memory consumption - XmlWriter uses less memory than XmlDocument, which is only an issue if you write very big files though. Another important difference is that when using XmlDocument, you can read an existing file, manipulate it and then write back the changes. With XmlWriter, you will have to write the entire document from scratch each time. This is not necessarily a problem though, so as always, it really comes down to your situation as well as your personal preferences.

Here's an example of writing XML using the XmlWriter class:

using System;
using System.Text;
using System.Xml;

namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlWriter xmlWriter = XmlWriter.Create("test.xml");

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("users");

            xmlWriter.WriteStartElement("user");
            xmlWriter.WriteAttributeString("age", "42");
            xmlWriter.WriteString("John Doe");
            xmlWriter.WriteEndElement();

            xmlWriter.WriteStartElement("user");
            xmlWriter.WriteAttributeString("age", "39");
            xmlWriter.WriteString("Jane Doe");

            xmlWriter.WriteEndDocument();
            xmlWriter.Close();
        }
    }
}

 The above code will create the following XML:

<users>
  <user age="42">John Doe</user>
  <user age="39">Jane Doe</user>
</users>

 So, we start by creating an instance of the XmlWriter class. It takes at least one parameter, in this case the path to where the XML should be written, but comes in many variations for various purposes. The first thing we should do is to call the WriteStartDocument() method. After that, we write a start element called "users". The XmlWriter will translate this into <users>. Before closing it, we write another start element, "user", which will then become a child of "users". We then proceed to adding an attribute (age) to the element, using the WriteAttributeString() method, and then we write the inner text of the element, by calling the WriteString() method. We then make sure to close the first "user" element with a call to the WriteEndElement() method.

分享到:
评论

相关推荐

    NativeXml-master

    + Minor improvements in writing xml elements with XmlFormat := xfReadable Version 3.21 (04feb2011) ! Re-added sdStringToDateTime functions instead of non-functional StrToDateTime ! Fixed function ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    - fixed bug in XML export with the ShowProgress property - fixed bug in RTF export with font size in empty cells - fixed bug in ODF export with UTF8 encoding of the Creator field - fixed bug in XML ...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...PEP 343: The ‘with...

    PHP5 完整官方 中文教程

    XMLWriter — XMLWriter Functions XSL — XSL functions XSLT — XSLT Functions YAZ — YAZ Functions YP/NIS — YP/NIS Functions Zip — Zip File Functions Zlib — Zlib Compression Functions PHP at the ...

    PHP5中文参考手册

    XMLWriter — XMLWriter Functions XSL — XSL functions XSLT — XSLT Functions YAZ — YAZ Functions YP/NIS — YP/NIS Functions Zip — Zip File Functions Zlib — Zlib Compression Functions PHP at the ...

    PHP官方手册中文版

    XMLWriter Functions CLXXXIV. XSL functions CLXXXV. XSLT Functions CLXXXVI. YAZ Functions CLXXXVII. YP/NIS Functions CLXXXVIII. Zip File Functions CLXXXIX. Zlib Compression Functions VII. ...

    PHP手册2007整合中文版

    XMLWriter Functions CLXXXIV. XSL functions CLXXXV. XSLT Functions CLXXXVI. YAZ Functions CLXXXVII. YP/NIS Functions CLXXXVIII. Zip File Functions CLXXXIX. Zlib Compression Functions VII. PHP at the ...

    输出Log到SD卡

    public class FileLogger { private static final String TAG = "FileLogger"; private static final String LOG_FILE_NAME = "app_log.txt"; public static void writeLog(String logMessage) { try { File ...

    android工具类-外部存储的缓存文件

    在Android开发中,工具类(Util Class)是程序员经常创建的一种辅助类,它们通常包含一组静态方法,用于执行特定的任务,比如处理数据、提供便利功能等。本篇将重点讲解如何在Android中创建一个用于管理外部存储缓存...

    加速度计示例和记录

    public class MainActivity extends AppCompatActivity implements SensorEventListener { private SensorManager sensorManager; private Sensor accelerometer; @Override protected void onCreate(Bundle ...

Global site tag (gtag.js) - Google Analytics