XmlTextReader.ReadString 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
以字符串形式读取元素或文本节点的内容。
public:
override System::String ^ ReadString();
public override string ReadString();
override this.ReadString : unit -> string
Public Overrides Function ReadString () As String
返回
元素或文本节点的内容。 如果读取器位于除元素或文本节点以外的内容上,或者当前上下文中没有要返回的文本内容,则可以为空字符串。
Note: 文本节点可以是元素或属性文本节点。
例外
分析 XML 时出错。
尝试了无效的操作。
示例
以下示例显示每个元素的文本内容。
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlTextReader reader = null;
try
{
//Load the reader with the XML file.
reader = new XmlTextReader("elems.xml");
//Parse the XML and display the text content of each of the elements.
while (reader.Read()){
if (reader.IsStartElement()){
if (reader.IsEmptyElement)
{
Console.WriteLine("<{0}/>", reader.Name);
}
else
{
Console.Write("<{0}> ", reader.Name);
reader.Read(); //Read the start tag.
if (reader.IsStartElement()) //Handle nested elements.
Console.Write("\r\n<{0}>", reader.Name);
Console.WriteLine(reader.ReadString()); //Read the text content of the element.
}
}
}
}
finally
{
if (reader != null)
reader.Close();
}
}
} // End class
Option Strict
Option Explicit
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim reader As XmlTextReader = Nothing
Try
'Load the reader with the XML file.
reader = New XmlTextReader("elems.xml")
'Parse the XML and display the text content of each of the elements.
While reader.Read()
If reader.IsStartElement() Then
If reader.IsEmptyElement Then
Console.WriteLine("<{0}/>", reader.Name)
Else
Console.Write("<{0}>" + " ", reader.Name)
reader.Read() 'Read the start tag.
If (reader.IsStartElement()) 'Handle nested elements.
Console.WriteLine()
Console.Write("<{0}>", reader.Name)
End If
Console.WriteLine(reader.ReadString()) 'Read the text content of the element.
End If
End If
End While
Finally
If Not (reader Is Nothing) Then
reader.Close()
End If
End Try
End Sub
End Class
该示例使用该文件 elems.xml作为输入。
<book>
<title>Pride And Prejudice</title>
<price>19.95</price>
<misc/>
</book>
注解
注释
建议您使用XmlReader方法创建XmlReader.Create实例,以利用新功能。
如果定位在元素上, ReadString 则将所有文本、重要空格、空格和 CData 节节点类型连接在一起,并将串联的数据作为元素内容返回。 当遇到任何标记(包括注释和处理指令)时,它将停止。 这可能发生在混合内容模型中,或者在读取元素结束标记时发生。
如果定位在文本节点上, ReadString 则从文本节点到元素结束标记执行相同的串联。 如果读取器位于属性文本节点上, ReadString 则具有与读取器位于元素开始标记上的位置相同的功能。 它返回所有串联的元素文本节点。