XmlDocument.CreateTextNode(String) 方法

定义

创建具有指定文本的 XmlText

public:
 virtual System::Xml::XmlText ^ CreateTextNode(System::String ^ text);
public virtual System.Xml.XmlText CreateTextNode (string text);
public virtual System.Xml.XmlText CreateTextNode (string? text);
abstract member CreateTextNode : string -> System.Xml.XmlText
override this.CreateTextNode : string -> System.Xml.XmlText
Public Overridable Function CreateTextNode (text As String) As XmlText

参数

text
String

Text 节点的文本。

返回

XmlText

新的 XmlText 节点。

示例

以下示例创建一个新元素并将其添加到文档中。

#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

注解

尽管此方法在文档上下文中创建新对象,但它不会自动将新对象添加到文档树。 若要添加新对象,必须显式调用其中一个节点插入方法。

根据 W3C 可扩展标记语言 (XML) 1.0 建议,文本节点只能在元素、属性和 EntityReference 节点内使用。

适用于