XmlDocument.CreateElement Método

Definición

Crea una interfaz XmlElement.

Sobrecargas

Nombre Description
CreateElement(String)

Crea un elemento con el nombre especificado.

CreateElement(String, String)

Crea un XmlElement objeto con el nombre completo y NamespaceURI.

CreateElement(String, String, String)

Crea un elemento con el especificado Prefix, LocalNamey NamespaceURI.

CreateElement(String)

Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs

Crea un elemento con el nombre especificado.

public:
 System::Xml::XmlElement ^ CreateElement(System::String ^ name);
public System.Xml.XmlElement CreateElement(string name);
member this.CreateElement : string -> System.Xml.XmlElement
Public Function CreateElement (name As String) As XmlElement

Parámetros

name
String

Nombre completo del elemento. Si el nombre contiene dos puntos, la Prefix propiedad refleja la parte del nombre que precede a los dos puntos y la LocalName propiedad refleja la parte del nombre después de los dos puntos. El nombre completo no puede incluir un prefijo de "xmlns".

Devoluciones

El nuevo XmlElement.

Ejemplos

En el ejemplo siguiente se crea un nuevo elemento y se agrega al documento.

using System;
using System.Xml;

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

    // 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);
  }
}
Imports System.IO
Imports System.Xml

Public Class Sample
    Public Shared Sub Main()

        ' Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>"  & _
                    "<title>Pride And Prejudice</title>"  & _
                    "</book>")

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

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

    End Sub
End Class

En el ejemplo se genera la siguiente salida:

Display the modified XML...
<?xml version="1.0" encoding="utf-8"?>
<book genre="novel" ISBN="1-861001-57-5">
  <title>Pride And Prejudice</title>
  <price>19.95</price>
</book>

Comentarios

Tenga en cuenta que la instancia devuelta implementa la XmlElement interfaz, por lo que los atributos predeterminados se crearían directamente en el objeto devuelto.

Aunque este método crea el nuevo objeto en el contexto del documento, no agrega automáticamente el nuevo objeto al árbol de documentos. Para agregar el nuevo objeto, debe llamar explícitamente a uno de los métodos de inserción de nodo.

Según la recomendación W3C Extensible Markup Language (XML) 1.0, los nodos Element se permiten en los nodos Document y Element y en los nodos EntityReference cuando el nodo EntityReference no es un elemento secundario de un nodo Attribute.

Se aplica a

CreateElement(String, String)

Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs

Crea un XmlElement objeto con el nombre completo y NamespaceURI.

public:
 System::Xml::XmlElement ^ CreateElement(System::String ^ qualifiedName, System::String ^ namespaceURI);
public System.Xml.XmlElement CreateElement(string qualifiedName, string namespaceURI);
public System.Xml.XmlElement CreateElement(string qualifiedName, string? namespaceURI);
member this.CreateElement : string * string -> System.Xml.XmlElement
Public Function CreateElement (qualifiedName As String, namespaceURI As String) As XmlElement

Parámetros

qualifiedName
String

Nombre completo del elemento. Si el nombre contiene dos puntos, la Prefix propiedad reflejará la parte del nombre que precede a los dos puntos y la LocalName propiedad reflejará la parte del nombre después de los dos puntos. El nombre completo no puede incluir un prefijo de "xmlns".

namespaceURI
String

Identificador URI del espacio de nombres del elemento.

Devoluciones

El nuevo XmlElement.

Comentarios

El código de C# siguiente:

XmlElement elem;
elem=doc.CreateElement("xy:item", "urn:abc");

... da como resultado un elemento equivalente al siguiente XML.

<xy:item
       xmlns:xy="urn:abc"/>

Aunque este método crea el nuevo objeto en el contexto del documento, no agrega automáticamente el nuevo objeto al árbol de documentos. Para agregar el nuevo objeto, debe llamar explícitamente a uno de los métodos de inserción de nodo.

Según la recomendación W3C Extensible Markup Language (XML) 1.0, los nodos Element se permiten en los nodos Document y Element y en los nodos EntityReference cuando el nodo EntityReference no es un elemento secundario de un nodo Attribute.

Se aplica a

CreateElement(String, String, String)

Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs
Source:
XmlDocument.cs

Crea un elemento con el especificado Prefix, LocalNamey NamespaceURI.

public:
 virtual System::Xml::XmlElement ^ CreateElement(System::String ^ prefix, System::String ^ localName, System::String ^ namespaceURI);
public virtual System.Xml.XmlElement CreateElement(string prefix, string localName, string namespaceURI);
public virtual System.Xml.XmlElement CreateElement(string? prefix, string localName, string? namespaceURI);
abstract member CreateElement : string * string * string -> System.Xml.XmlElement
override this.CreateElement : string * string * string -> System.Xml.XmlElement
Public Overridable Function CreateElement (prefix As String, localName As String, namespaceURI As String) As XmlElement

Parámetros

prefix
String

Prefijo del nuevo elemento (si existe). String.Empty y null son equivalentes.

localName
String

Nombre local del nuevo elemento.

namespaceURI
String

URI del espacio de nombres del nuevo elemento (si existe). String.Empty y null son equivalentes.

Devoluciones

El nuevo XmlElement.

Ejemplos

En el ejemplo siguiente se agrega un nuevo elemento al documento XML existente.

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

public class Sample1
{
  public static void CreateElementExample()
  {
    // Create the XmlDocument.
    XmlDocument doc = new();
    string xmlData = "<book xmlns:bk='urn:samples'></book>";

    doc.Load(new StringReader(xmlData));

    // Create a new element and add it to the document.
    XmlElement elem = doc.CreateElement("bk", "genre", "urn:samples");
    elem.InnerText = "fantasy";
    doc.DocumentElement.AppendChild(elem);

    Console.WriteLine("Display the modified XML...");
    doc.Save(Console.Out);
  }
}
Imports System.IO
Imports System.Xml

public class Sample 

  public shared sub Main() 

    ' Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    Dim xmlData as string = "<book xmlns:bk='urn:samples'></book>"

    doc.Load(new StringReader(xmlData))

    ' Create a new element and add it to the document.
    Dim elem as XmlElement = doc.CreateElement("bk", "genre", "urn:samples")
    elem.InnerText = "fantasy"
    doc.DocumentElement.AppendChild(elem)

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

  end sub
end class

Comentarios

El código de C# siguiente:

XmlElement elem;
elem=doc.CreateElement("xy", "item", "urn:abc");

... crea un elemento equivalente al siguiente XML:

<xy:item xmlns:xy="urn:abc"/>

Aunque este método crea el nuevo objeto en el contexto del documento, no agrega automáticamente el nuevo objeto al árbol de documentos. Para agregar el nuevo objeto, debe llamar explícitamente a uno de los métodos de inserción de nodo.

Según la recomendación W3C Extensible Markup Language (XML) 1.0, los nodos Element se permiten en los nodos Document y Element y en los nodos EntityReference cuando EntityReference está fuera de un nodo Attribute.

Este método es una extensión Microsoft al modelo de objetos de documento (DOM).

Se aplica a