XmlDocument.CreateEntityReference(String) Método

Definición

Crea un objeto XmlEntityReference con el nombre especificado.

public:
 virtual System::Xml::XmlEntityReference ^ CreateEntityReference(System::String ^ name);
public virtual System.Xml.XmlEntityReference CreateEntityReference (string name);
abstract member CreateEntityReference : string -> System.Xml.XmlEntityReference
override this.CreateEntityReference : string -> System.Xml.XmlEntityReference
Public Overridable Function CreateEntityReference (name As String) As XmlEntityReference

Parámetros

name
String

Nombre de la referencia a entidad.

Devoluciones

XmlEntityReference

Nuevo objeto XmlEntityReference.

Excepciones

El nombre no es válido (por ejemplo, los nombres que empiezan por “#” no son válidos).

Ejemplos

En el ejemplo siguiente se crean dos nodos de referencia de entidad y se insertan en un documento XML.

#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( "<!DOCTYPE book [<!ENTITY h 'hardcover'>]><book genre='novel' ISBN='1-861001-57-5'><title>Pride And Prejudice</title><misc/></book>" );
   
   //Create an entity reference node. The child count should be 0 
   //since the node has not been expanded.
   XmlEntityReference^ entityref = doc->CreateEntityReference( "h" );
   Console::WriteLine( entityref->ChildNodes->Count );
   
   //After the node has been added to the document, its parent node
   //is set and the entity reference node is expanded.  It now has a child
   //node containing the entity replacement text. 
   doc->DocumentElement->LastChild->AppendChild( entityref );
   Console::WriteLine( entityref->FirstChild->InnerText );
   
   //Create and insert an undefined entity reference node.  When the entity
   //reference node is expanded, because the entity reference is undefined
   //the child is an empty text node.
   XmlEntityReference^ entityref2 = doc->CreateEntityReference( "p" );
   doc->DocumentElement->LastChild->AppendChild( entityref2 );
   Console::WriteLine( entityref2->FirstChild->InnerText );
}

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

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" +
                "<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "<misc/>" +
                "</book>");

    //Create an entity reference node. The child count should be 0
    //since the node has not been expanded.
    XmlEntityReference entityref = doc.CreateEntityReference("h");
    Console.WriteLine(entityref.ChildNodes.Count );

    //After the node has been added to the document, its parent node
    //is set and the entity reference node is expanded.  It now has a child
    //node containing the entity replacement text.
    doc.DocumentElement.LastChild.AppendChild(entityref);
    Console.WriteLine(entityref.FirstChild.InnerText);

    //Create and insert an undefined entity reference node.  When the entity
    //reference node is expanded, because the entity reference is undefined
    //the child is an empty text node.
    XmlEntityReference entityref2 = doc.CreateEntityReference("p");
    doc.DocumentElement.LastChild.AppendChild(entityref2);
    Console.WriteLine(entityref2.FirstChild.InnerText);
  }
}
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("<!DOCTYPE book [<!ENTITY h 'hardcover'>]>" & _
                    "<book genre='novel' ISBN='1-861001-57-5'>"  & _
                    "<title>Pride And Prejudice</title>"  & _
                    "<misc/>"  & _
                    "</book>")
        
        'Create an entity reference node. The child count should be 0 
        'since the node has not been expanded.
        Dim entityref As XmlEntityReference = doc.CreateEntityReference("h")
        Console.WriteLine(entityref.ChildNodes.Count)
        
        'After the node has been added to the document, its parent node
        'is set and the entity reference node is expanded.  It now has a child
        'node containing the entity replacement text. 
        doc.DocumentElement.LastChild.AppendChild(entityref)
        Console.WriteLine(entityref.FirstChild.InnerText)
        
        'Create and insert an undefined entity reference node.  When the entity
        'reference node is expanded, because the entity reference is undefined
        'the child is an empty text node.
        Dim entityref2 As XmlEntityReference = doc.CreateEntityReference("p")
        doc.DocumentElement.LastChild.AppendChild(entityref2)
        Console.WriteLine(entityref2.FirstChild.InnerText)
    End Sub
End Class

Comentarios

Si se conoce la entidad a la que se hace referencia, la lista secundaria del XmlEntityReference nodo se realiza igual que la del nodo correspondiente XmlEntity .

Los espacios de nombres usados en el texto de reemplazo de la referencia de entidad se enlazan en el momento en que el elemento primario del nodo de referencia de entidad se establece por primera vez (por ejemplo, cuando se inserta el nodo de referencia de entidad en el documento). Por ejemplo, dada la siguiente entidad:

<!ENTITY a "<b>test</b>">  

Si llama a CreateEntityReference("a") , devuelve un único nodo de tipo EntityReference sin elementos secundarios. Si anexa este nodo como elemento secundario del siguiente nodo,

<item xmlns="urn:1"/>  

a continuación, en el momento de llamar a AppendChild, se establece el elemento primario del nodo de referencia de entidad recién creado y los elementos secundarios se expanden en este contexto de espacio de nombres. El nodo b de elemento secundario tendrá namespaceURI igual a urn:1. Los nodos secundarios de la referencia de entidad siguen siendo los mismos incluso si mueve la referencia de entidad a un lugar en el documento que tiene un contexto de espacio de nombres predeterminado diferente. Esto no sucede para los nodos de referencia de entidad existentes al quitarlos e insertarlos o para las referencias de entidad que clone con CloneNode. Solo se produce para las referencias de entidad recién creadas.

Si la entidad correspondiente no está definida en documentType cuando se agrega el nodo de referencia de entidad, porque la referencia de entidad no está definida, su único nodo secundario será un nodo de texto vacío.

También se permiten las entidades integradas amp, lt, gt, ap y quot, y tendrán un nodo de texto secundario con el valor de carácter expandido adecuado.

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 EntityReference solo se permiten en nodos Element, Attribute y EntityReference.

Se aplica a