XmlReader.ReadSubtree 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回可用于读取当前节点及其所有后代的新 XmlReader 实例。
public:
virtual System::Xml::XmlReader ^ ReadSubtree();
public virtual System.Xml.XmlReader ReadSubtree();
abstract member ReadSubtree : unit -> System.Xml.XmlReader
override this.ReadSubtree : unit -> System.Xml.XmlReader
Public Overridable Function ReadSubtree () As XmlReader
返回
一个新的 XML 读取器实例设置为 Initial。 调用该方法会将 Read() 新读取器放置在调用 ReadSubtree() 方法之前当前节点上。
例外
调用此方法时,XML 读取器不会定位在元素上。
-或-
在上一个异步操作完成之前调用了一个 XmlReader 方法。 在这种情况下, InvalidOperationException 会引发消息“正在进行异步操作”。
示例
以下示例演示如何使用 ReadSubtree 该方法。
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
using (XmlReader reader = XmlReader.Create("books.xml", settings)) {
// Position the reader on the second book node
reader.ReadToFollowing("Book");
reader.Skip();
// Create another reader that contains just the second book node.
XmlReader inner = reader.ReadSubtree();
inner.ReadToDescendant("Title");
Console.WriteLine(inner.Name);
// Do additional processing on the inner reader. After you
// are done, call Close on the inner reader and
// continue processing using the original reader.
inner.Close();
}
Dim settings As New XmlReaderSettings()
settings.IgnoreWhitespace = True
Using reader As XmlReader = XmlReader.Create("books.xml", settings)
' Position the reader on the second book node.
reader.ReadToFollowing("Book")
reader.Skip()
' Create another reader that contains just the second book node.
Dim inner As XmlReader = reader.ReadSubtree()
inner.ReadToDescendant("Title")
Console.WriteLine(inner.Name)
' Do additional processing on the inner reader. After you
' are done, call Close on the inner reader and
' continue processing using the original reader.
inner.Close()
End Using
使用以下 XML 数据运行本主题中的示例:
<?xml version="1.0" encoding="utf-8" ?>
<Books>
<Book>
<Title>A Brief History of Time</Title>
</Book>
<Book>
<Title>Principle Of Relativity</Title>
</Book>
<Book>
<Title>Victory of Reason</Title>
</Book>
<Book>
<Title>The Unicorn that did not Fail</Title>
</Book>
<Book>
<Title>Rational Ontology</Title>
</Book>
<Book>
<Title>The Meaning of Pizza</Title>
</Book>
</Books>
注解
ReadSubtree 只能在元素节点上调用。 读取整个子树后,对方法的 Read 调用将 false返回。 当新的 XML 读取器关闭时,原始读取器将定位在 EndElement 子树的节点上。 因此,如果在 book 元素的起始标记上调用 ReadSubtree 该方法,在读取子树并关闭新的 XML 读取器后,原始 XML 读取器将定位在 book 元素的结束标记上。
在新读取器关闭之前,不应对原始读取器执行任何操作。 此操作不受支持,可能会导致不可预知的行为。
注释
该方法 ReadSubtree 不适用于创建可以独立使用的 XML 数据的副本。 它旨在围绕 XML 元素创建边界。 如果要将数据传递给另一个组件进行处理,并且希望限制该组件可以访问的数据量,这非常有用。 将方法返回的 ReadSubtree XML 读取器传递给另一个应用程序时,应用程序只能访问该 XML 元素,而不能访问整个 XML 文档。