XmlDocument.CreateEntityReference(String) Метод

Определение

Создает объект XmlEntityReference с указанным именем.

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

Параметры

name
String

Имя ссылки на сущность.

Возвращаемое значение

XmlEntityReference

Новый объект XmlEntityReference.

Исключения

Недопустимое имя (например, имена, начинающиеся с символа "#", являются недопустимыми.)

Примеры

В следующем примере создаются два узла ссылки на сущности и их вставка в 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

Комментарии

Если упоминаемая сущность известна, дочерний список XmlEntityReference узла создается так же, как и соответствующий XmlEntity узел.

Пространства имен, используемые в замещаемом тексте ссылки на сущность, привязаны во время первого задания родительского узла ссылки на сущность (например, при вставке узла ссылки на сущность в документ). Например, учитывая следующую сущность:

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

При вызове CreateEntityReference("a") возвращается один узел типа EntityReference без дочерних элементов. Если добавить этот узел в качестве дочернего элемента следующего узла,

<item xmlns="urn:1"/>  

Затем во время вызова AppendChildзадается родительский элемент только что созданного узла ссылки на сущность, а дочерние элементы расширяются в этом контексте пространства имен. Узел дочернего элемента b будет иметь namespaceURI, равный urn:1. Дочерние узлы ссылки на сущность остаются неизменными, даже если переместить ссылку на сущность на место в документе с другим контекстом пространства имен по умолчанию. Это не происходит для существующих узлов ссылок на сущности при удалении и вставке и вставке ссылок на сущности, с которыми CloneNodeвы клонируете. Это происходит только для вновь созданных ссылок на сущности.

Если соответствующая сущность не определена в DocumentType при добавлении узла ссылки на сущность, так как ссылка на сущность не определена, его единственный дочерний узел будет пустым текстовым узлом.

Встроенные сущности amp, lt, apos и quot также разрешены, и они будут иметь дочерний текстовый узел с соответствующим расширенным значением символа.

Хотя этот метод создает новый объект в контексте документа, он не добавляет новый объект в дерево документов автоматически. Чтобы добавить новый объект, необходимо явно вызвать один из методов вставки узла.

В соответствии с рекомендацией W3C Extensible Markup Language (XML) 1.0 узлы EntityReference разрешены только в узлах Element, Attribute и EntityReference.

Применяется к