XmlDocument.CreateEntityReference(String) Método

Definição

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

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

O nome da referência da entidade.The name of the entity reference.

Retornos

XmlEntityReference

O novo XmlEntityReference.The new XmlEntityReference.

Exceções

O nome é inválido (por exemplo, nomes que começam com '#' são inválidos.)The name is invalid (for example, names starting with'#' are invalid.)

Exemplos

O exemplo a seguir cria dois nós de referência de entidade e os insere em um documento XML.The following example creates two entity reference nodes and inserts them into an 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;
   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

Comentários

Se a entidade referenciada for conhecida, a lista filho do XmlEntityReference nó será feita da mesma forma que a do XmlEntity nó correspondente.If the referenced entity is known, the child list of the XmlEntityReference node is made the same as that of the corresponding XmlEntity node.

Os namespaces usados no texto de substituição para a referência de entidade são associados no momento em que o pai do nó de referência de entidade é definido primeiro (por exemplo, quando o nó de referência de entidade é inserido no documento).The namespaces used in the replacement text for the entity reference are bound at the time the parent of the entity reference node is first set (for example, when the entity reference node is inserted into the document). Por exemplo, considerando a seguinte entidade:For example, given the following entity:

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

Se você chamar CreateEntityReference("a") , obterá um único nó do tipo EntityReference sem filhos.If you call CreateEntityReference("a") you get back a single node of type EntityReference with no children. Se você acrescentar este nó como um filho do nó a seguir,If you append this node as a child of the following node,

<item xmlns="urn:1"/>  

em seguida, no momento da chamada AppendChild , o pai do nó de referência de entidade recém criada é definido e os filhos são expandidos nesse contexto de namespace.then, at the time of calling AppendChild, the parent of the newly created entity reference node is set and the children are expanded in this namespace context. O nó do elemento filho terá b NamespaceURI igual a urn:1 .The child element node b will have NamespaceURI equal to urn:1. Os nós filho da referência de entidade permanecem os mesmos mesmo se você mover a referência de entidade para um local no documento que tem um contexto de namespace padrão diferente.The child nodes of the entity reference remain the same even if you move the entity reference to a place in the document that has a different default namespace context. Isso não acontece para nós de referência de entidade existentes quando você os remove e insere ou para referências de entidade com as quais você clona CloneNode .This does not happen for existing entity reference nodes when you remove and insert them or for entity references that you clone with CloneNode. Isso ocorre apenas para referências de entidade recém-criadas.It only happens for newly created entity references.

Se a entidade correspondente não estiver definida no DocumentType quando o nó de referência de entidade for adicionado, porque a referência de entidade não está definida, seu único nó filho será um nó de texto vazio.If the corresponding entity is not defined in the DocumentType when the entity reference node is added, because the entity reference is not defined, its only child node will be an empty text node.

As entidades internas amp, lt, gt, apos e quot também são permitidas e terão um nó de texto filho com o valor de caractere expandido apropriado.The built-in entities amp, lt, gt, apos, and quot are also allowed, and they will have a child text node with the appropriate expanded character value.

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, os nós de EntityReference são permitidos somente dentro de elementos, atributos e nós EntityReference.According to the W3C Extensible Markup Language (XML) 1.0 recommendation, EntityReference nodes are only allowed within Element, Attribute and EntityReference nodes.

Aplica-se a