XmlDocument.CreateElement Método

Definição

Cria um XmlElement.Creates an XmlElement.

Sobrecargas

CreateElement(String)

Cria um elemento com o nome especificado.Creates an element with the specified name.

CreateElement(String, String)

Cria um XmlElement com o nome qualificado e NamespaceURI.Creates an XmlElement with the qualified name and NamespaceURI.

CreateElement(String, String, String)

Cria um elemento com o Prefix, LocalName e NamespaceURI especificados.Creates an element with the specified Prefix, LocalName, and NamespaceURI.

CreateElement(String)

Cria um elemento com o nome especificado.Creates an element with the specified name.

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

O nome qualificado do elemento.The qualified name of the element. Se o nome contiver dois-pontos, a propriedade Prefix refletirá a parte do nome anterior a ele e a propriedade LocalName refletirá a parte posterior a ele.If the name contains a colon then the Prefix property reflects the part of the name preceding the colon and the LocalName property reflects the part of the name after the colon. O nome qualificado não pode incluir um prefixo ‘xmlns’.The qualified name cannot include a prefix of 'xmlns'.

Retornos

XmlElement

O novo XmlElement.The new XmlElement.

Exemplos

O exemplo a seguir cria um novo elemento e o adiciona ao documento.The following example creates a new element and adds it to the document.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew 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.
   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 );
}

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

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = 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.
    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);
  }
}
Option Explicit
Option Strict

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

Comentários

Observe que a instância retornada implementa a XmlElement interface, portanto, os atributos padrão seriam criados diretamente no objeto retornado.Note that the instance returned implements the XmlElement interface, so default attributes would be created directly on the returned object.

Embora esse método crie o novo objeto no contexto do documento, ele não adiciona automaticamente o novo objeto à árvore de documentos.Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. Para adicionar o novo objeto, você deve chamar explicitamente um dos métodos de inserção de nó.To add the new object, you must explicitly call one of the node insert methods.

De acordo com a recomendação do W3C linguagem XML (XML) 1,0, nós de elemento são permitidos dentro de nós de documento e de elemento e em nós EntityReference quando o nó EntityReference não é filho de um nó de atributo.According to the W3C Extensible Markup Language (XML) 1.0 recommendation, Element nodes are allowed within Document and Element nodes, and in EntityReference nodes when the EntityReference node is not a child of an Attribute node.

Aplica-se a

CreateElement(String, String)

Cria um XmlElement com o nome qualificado e NamespaceURI.Creates an XmlElement with the qualified name and 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

O nome qualificado do elemento.The qualified name of the element. Se o nome contiver dois-pontos, a propriedade Prefix refletirá a parte do nome anterior aos dois-pontos e a propriedade LocalName refletirá a parte do nome posterior a ele.If the name contains a colon then the Prefix property will reflect the part of the name preceding the colon and the LocalName property will reflect the part of the name after the colon. O nome qualificado não pode incluir um prefixo ‘xmlns’.The qualified name cannot include a prefix of 'xmlns'.

namespaceURI
String

O URI do namespace do elemento.The namespace URI of the element.

Retornos

XmlElement

O novo XmlElement.The new XmlElement.

Comentários

O código C# a seguirThe following C# code

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

resulta em um elemento que é equivalente ao texto XML a seguir.results in an element that is equivalent to the following XML text.

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

Embora esse método crie o novo objeto no contexto do documento, ele não adiciona automaticamente o novo objeto à árvore de documentos.Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. Para adicionar o novo objeto, você deve chamar explicitamente um dos métodos de inserção de nó.To add the new object, you must explicitly call one of the node insert methods.

De acordo com a recomendação do W3C linguagem XML (XML) 1,0, nós de elemento são permitidos dentro de nós de documento e de elemento e em nós EntityReference quando o nó EntityReference não é filho de um nó de atributo.According to the W3C Extensible Markup Language (XML) 1.0 recommendation, Element nodes are allowed within Document and Element nodes, and in EntityReference nodes when the EntityReference node is not a child of an Attribute node.

Aplica-se a

CreateElement(String, String, String)

Cria um elemento com o Prefix, LocalName e NamespaceURI especificados.Creates an element with the specified Prefix, LocalName, and 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

O prefixo do novo elemento (se houver).The prefix of the new element (if any). String.Empty e null são equivalentes.String.Empty and null are equivalent.

localName
String

O nome local do novo elemento.The local name of the new element.

namespaceURI
String

O URI do namespace do novo elemento (se houver).The namespace URI of the new element (if any). String.Empty e null são equivalentes.String.Empty and null are equivalent.

Retornos

XmlElement

O novo XmlElement.The new XmlElement.

Exemplos

O exemplo a seguir adiciona um novo elemento ao documento XML existente.The following example adds a new element to the existing XML document.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   // Create the XmlDocument.
   XmlDocument^ doc = gcnew XmlDocument;
   String^ xmlData = "<book xmlns:bk='urn:samples'></book>";
   doc->Load( gcnew 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 );
}

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

public class Sample {

  public static void Main() {

    // Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    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

Comentários

O código C# a seguirThe following C# code

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

Cria um elemento equivalente ao seguinte texto XML:creates an element equivalent to the following XML text:

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

Embora esse método crie o novo objeto no contexto do documento, ele não adiciona automaticamente o novo objeto à árvore de documentos.Although this method creates the new object in the context of the document, it does not automatically add the new object to the document tree. Para adicionar o novo objeto, você deve chamar explicitamente um dos métodos de inserção de nó.To add the new object, you must explicitly call one of the node insert methods.

De acordo com a recomendação do W3C linguagem XML (XML) 1,0, nós de elemento são permitidos dentro de nós de documento e de elemento e em nós EntityReference quando a EntityReference está fora de um nó de atributo.According to the W3C Extensible Markup Language (XML) 1.0 recommendation, Element nodes are allowed within Document and Element nodes, and in EntityReference nodes when the EntityReference is outside an Attribute node.

Esse método é uma extensão da Microsoft para o Modelo de Objeto do Documento (DOM).This method is a Microsoft extension to the Document Object Model (DOM).

Aplica-se a