XmlTextReader.ReadAttributeValue 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將屬性值解析成一個或多個 Text、 EntityReference或 EndEntity 節點。
public:
override bool ReadAttributeValue();
public override bool ReadAttributeValue();
override this.ReadAttributeValue : unit -> bool
Public Overrides Function ReadAttributeValue () As Boolean
傳回
true 如果有節點需要回傳的話。
false 如果讀取器在初始呼叫時未位於屬性節點上,或所有屬性值都已被讀取。
空屬性,例如 , misc=""會以一個節點回傳 true ,其值為 String.Empty。
範例
以下範例讀取一個屬性,並包含文字節點與實體節點。
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlTextReader reader = null;
try
{
//Create the XML fragment to be parsed.
string xmlFrag ="<book genre='novel' misc='sale-item &h; 1987'></book>";
//Create the XmlParserContext.
XmlParserContext context;
string subset = "<!ENTITY h 'hardcover'>";
context = new XmlParserContext(null, null, "book", null, null, subset, "", "", XmlSpace.None);
//Create the reader.
reader = new XmlTextReader(xmlFrag, XmlNodeType.Element, context);
//Read the misc attribute. The attribute is parsed
//into multiple text and entity reference nodes.
reader.MoveToContent();
reader.MoveToAttribute("misc");
while (reader.ReadAttributeValue()){
if (reader.NodeType==XmlNodeType.EntityReference)
Console.WriteLine("{0} {1}", reader.NodeType, reader.Name);
else
Console.WriteLine("{0} {1}", reader.NodeType, reader.Value);
}
}
finally
{
if (reader != null)
reader.Close();
}
}
} // End class
Imports System.IO
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim reader As XmlTextReader = Nothing
Try
' Create the XML fragment to be parsed.
Dim xmlFrag As String = "<book genre='novel' misc='sale-item &h; 1987'></book>"
Dim subset As String = "<!ENTITY h 'hardcover'>"
' Create the XmlParserContext.
Dim context As New XmlParserContext(Nothing, Nothing, "book", Nothing, Nothing, subset, "", "", XmlSpace.None)
'Create the reader.
reader = New XmlTextReader(xmlFrag, XmlNodeType.Element, context)
'Read the misc attribute. The attribute is parsed
'into multiple text and entity reference nodes.
reader.MoveToContent()
reader.MoveToAttribute("misc")
While (reader.ReadAttributeValue())
If (reader.NodeType = XmlNodeType.EntityReference)
Console.WriteLine($"{reader.NodeType} {reader.Name}")
Else
Console.WriteLine($"{reader.NodeType} {reader.Value}")
End If
End While
Finally
If reader IsNot Nothing
reader.Close()
End if
End Try
End Sub
End Class
備註
備註
建議您使用 XmlReader 方法來建立XmlReader.Create實例,以利用新功能。
呼叫後 MoveToAttribute 使用此方法,讀取構成屬性值的文字或實體參考節點。 屬性值節點的 是 Depth 1 加上屬性節點的深度;當你進入或退出一般實體參考時,深度會增加或減少一。