System.Xml.XmlDocument.CreateNode 方法 (XmlNodeType, String, String, String)

方法描述

创建一个具有指定的 XmlNodeType、Prefix、Name 和 NamespaceURI 的 XmlNode。

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

public virtual XmlNode CreateNode(
	XmlNodeType type,
	string prefix,
	string name,
	string namespaceURI
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
type System-Xml-XmlNodeType 新节点的 XmlNodeType。
prefix System-String 新节点的前缀。
name System-String 新节点的本地名称。
namespaceURI System-String 新节点的命名空间 URI。
返回值 System.Xml.XmlNode 新的 XmlNode。

提示和注释

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

下表显示根据 W3C 可扩展标记语言 (XML) 1.0 建议 (www.w3.org/TR/1998/REC-xml-19980210),什么 NodeType[row] 可包含在另一个 NodeType[column] 中。

文档

DocumentType

XmlDeclaration

元素

特性

Text

CDATA

标记

EntityReference

Document

no

no

no

no

no

no

no

no

no

DocumentType

yes

no

no

no

no

no

no

no

no

XmlDeclaration

是*

no

no

no

no

no

no

no

no

Element

yes

no

no

yes

no

no

no

no

是***

Attribute

no

no

no

是****

no

no

no

no

no

Text

no

no

no

yes

yes

no

no

no

yes

CDATA

no

no

no

yes

no

no

no

no

是***

Markup**

yes

no

no

yes

no

no

no

no

no

EntityReference

no

no

no

yes

yes

no

no

no

yes

* XmlDeclaration 节点必须是 Document 节点的第一个子级。

** Markup 包含 ProcessingInstruction 和 Comment 节点。

*** 仅当 EntityReference 节点不是 Attribute 节点的子级时,Element 和 CDATA 节点才能包含在 EntityReference 节点中。

**** Attribute 不是 Element 节点的子级。 Attribute 包含在属于 Element 节点的特性集合中。

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

System.Xml.XmlDocument.CreateNode 方法 (XmlNodeType, String, String, String)例子

下面的示例将新元素添加到文档中。

using System;
using System.Xml;

public class Sample {

  public static void Main() {

       XmlDocument doc = new XmlDocument();
       doc.LoadXml("" +
                   "  Oberon's Legacy" +
                   "  5.95" +
                   ""); 

       // Create a new element node.
       XmlNode newElem;
       newElem = doc.CreateNode(XmlNodeType.Element, "pages", "");  
       newElem.InnerText = "290";

       Console.WriteLine("Add the new element to the document...");
       XmlElement root = doc.DocumentElement;
       root.AppendChild(newElem);

       Console.WriteLine("Display the modified XML document...");
       Console.WriteLine(doc.OuterXml);
   }
 }

异常

异常 异常描述
ArgumentException 未提供名称,而 XmlNodeType 需要名称。

命名空间

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