System.Xml.XmlWriter.WriteElementString 方法 (String, String, String)

方法描述

使用指定的本地名称、命名空间 URI 和值编写元素。

语法定义(C# System.Xml.XmlWriter.WriteElementString 方法 (String, String, String) 的用法)

public void WriteElementString(
	string localName,
	string ns,
	string value
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
localName System-String 元素的本地名称。
ns System-String 与元素关联的命名空间 URI。
value System-String 元素的值。
返回值 void

提示和注释

System.Xml.XmlWriter.WriteElementString 方法 (String, String, String)例子

下面的示例使用若干个写方法创建 XML 片段。

using System;
using System.IO;
using System.Xml;

 public class Sample
 {
   private const string m_Document = "sampledata.xml";

   public static void Main() {

      XmlWriter writer = null;

      try {

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        writer = XmlWriter.Create (m_Document, settings);

        writer.WriteComment("sample XML fragment");

        // Write an element (this one is the root).
        writer.WriteStartElement("book");

        // Write the namespace declaration.
        writer.WriteAttributeString("xmlns", "bk", null, "urn:samples");

        // Write the genre attribute.
        writer.WriteAttributeString("genre", "novel");

        // Write the title.
        writer.WriteStartElement("title");
        writer.WriteString("The Handmaid's Tale");
        writer.WriteEndElement();

        // Write the price.
        writer.WriteElementString("price", "19.95");

        // Lookup the prefix and write the ISBN element.
        string prefix = writer.LookupPrefix("urn:samples");
        writer.WriteStartElement(prefix, "ISBN", "urn:samples");
        writer.WriteString("1-861003-78");
        writer.WriteEndElement();

        // Write the style element (shows a different way to handle prefixes).
        writer.WriteElementString("style", "urn:samples", "hardcover");

        // Write the close tag for the root element.
        writer.WriteEndElement();

        // Write the XML to file and close the writer.
        writer.Flush();
        writer.Close();
      }

      finally {
        if (writer != null)
           writer.Close();
     } 
   }

 }

异常

异常 异常描述
ArgumentException
  • localName 值是 null 或空字符串。
  • 参数值无效。
EncoderFallbackException 缓冲区中有一个字符是有效的 XML 字符,但对于输出编码是无效的。 例如,如果输出编码为 ASCII,应该仅对元素和特性名使用从 0 到 127 范围内的字符。 无效的字符可能位于此方法的参数中,或者位于以前要写入缓冲区的方法的参数中。 如果可能,此类字符将使用字符实体引用进行转义(例如,在文本节点或特性值中)。 但是,不允许在元素名、特性名、注释、处理指令和 CDATA 节中使用字符实体引用。

命名空间

namespace: System.Xml

程序集: System.Xml(在 System.Xml.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。