System.Xml.XmlDocument.CreateElement 方法 (String)

方法描述

创建具有指定名称的元素。

语法定义(C# System.Xml.XmlDocument.CreateElement 方法 (String) 的用法)

public XmlElement CreateElement(
	string name
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
name System-String 元素的限定名。如果名称包含冒号,则 Prefix 属性反映名称中位于冒号之前的部分,LocalName 属性反映名称中位于冒号之后的部分。限定名不能包含“xmlns”前缀。
返回值 System.Xml.XmlElement 新的 XmlElement。

提示和注释

请注意返回的实例实现 XmlElement 接口,因此将在返回的对象上直接创建默认特性。

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

根据 W3C 可扩展标记语言 (XML) 1.0 建议 (www.w3.org/TR/1998/REC-xml-19980210),Element 节点可包含在 Document 节点和 Element 节点中,并且当 EntityReference 节点不是 Attribute 节点的子级时,Element 节点可包含在 EntityReference 节点中。

System.Xml.XmlDocument.CreateElement 方法 (String)例子

下面的示例创建一个新元素并将其添加到文档。

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

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("" +
                "Pride And Prejudice" +
                "");

    //Create a new node and add it to the document.
    //The text node is the content of the price element.
    XmlElement elem = doc.CreateElement("price");
    XmlText text = doc.CreateTextNode("19.95");
    doc.DocumentElement.AppendChild(elem);
    doc.DocumentElement.LastChild.AppendChild(text);

    Console.WriteLine("Display the modified XML...");
    doc.Save(Console.Out);

  }
}

异常

异常 异常描述

命名空间

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 系统要求。