XmlDocument.CreateXmlDeclaration(String, String, String) 方法

定义

XmlDeclaration创建具有指定值的节点。

public:
 virtual System::Xml::XmlDeclaration ^ CreateXmlDeclaration(System::String ^ version, System::String ^ encoding, System::String ^ standalone);
public virtual System.Xml.XmlDeclaration CreateXmlDeclaration(string version, string encoding, string standalone);
public virtual System.Xml.XmlDeclaration CreateXmlDeclaration(string version, string? encoding, string? standalone);
abstract member CreateXmlDeclaration : string * string * string -> System.Xml.XmlDeclaration
override this.CreateXmlDeclaration : string * string * string -> System.Xml.XmlDeclaration
Public Overridable Function CreateXmlDeclaration (version As String, encoding As String, standalone As String) As XmlDeclaration

参数

version
String

版本必须为“1.0”。

encoding
String

编码特性的值。 这是将文件或流保存到 XmlDocument 文件时使用的编码;因此,它必须设置为类支持的 Encoding 字符串,否则 Save(String) 会失败。 如果为 null String.Empty,则 Save 该方法不会在 XML 声明上写入编码属性,因此使用默认编码 UTF-8。

注意:如果保存到 XmlDocument 某个 TextWriter 或某个 XmlTextWriter值,则会放弃此编码值。 请改用或TextWriter使用该编码XmlTextWriter。 这可确保使用正确的编码读回 XML。

standalone
String

该值必须是“是”或“否”。 如果为 null String.Empty,则 Save 该方法不会在 XML 声明上编写独立属性。

返回

XmlDeclaration 节点。

例外

上面指定的值 versionstandalone 值以外的值。

示例

以下示例创建 XML 声明并将其添加到文档中。

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

public class Sample
{
  public static void Main()
  {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Create an XML declaration.
    XmlDeclaration xmldecl;
    xmldecl = doc.CreateXmlDeclaration("1.0",null,null);

    //Add the new node to the document.
    XmlElement root = doc.DocumentElement;
    doc.InsertBefore(xmldecl, root);

    Console.WriteLine("Display the modified XML...");
    doc.Save(Console.Out);
  }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml

Public Class Sample
    
    Public Shared Sub Main()
        Dim doc As New XmlDocument()
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "</book>")
        
        'Create an XML declaration. 
        Dim xmldecl As XmlDeclaration
        xmldecl = doc.CreateXmlDeclaration("1.0", Nothing, Nothing)
        
        'Add the new node to the document.
        Dim root As XmlElement = doc.DocumentElement
        doc.InsertBefore(xmldecl, root)
        
        Console.WriteLine("Display the modified XML...")
        doc.Save(Console.Out)
    End Sub
End Class

注解

这些属性作为节点上的特殊属性 XmlDeclaration 公开,而不是作为 XmlAttribute 节点公开。

尽管此方法在文档上下文中创建新对象,但它不会自动将新对象添加到文档树。 若要添加新对象,必须显式调用其中一个节点插入方法。

根据 W3C 可扩展标记语言 (XML) 1.0 建议,节点 XmlDeclaration 必须是文档中的第一个节点。

此方法是文档对象模型(DOM)的Microsoft扩展。

适用于

另请参阅