您的位置:首页 > 其它

XML 读取器和编写器----从流读取 XML

2006-12-06 19:01 211 查看

如何从流读取 XML 数据

此示例阐释如何使用 XmlTextReader 类从流读取 XML。流可能来自不同的源,如来自服务器、文件或 TextReader 的字节流。
注意:此示例是如何从文件读取 XML主题的继续。




VB ReadXmlStream.aspx
[运行示例] | [查看源代码]
XmlTextReader 有不同的构造函数,以指定 XML 数据的位置。此示例从流加载 XmlTextReader。流是作为数据(在这里是指 XML 数据)的源或目标的输入或输出设备的抽象表示形式。您可以写入流或读取流,流的最形象化表示是字节流。流可提供不依赖于设备的独立性,因此,如果当流的源更改时,它不要求程序也进行更改。
下列示例代码创建 StringReader 类,它可构成 XML 字符串。由于该字符串是保留在内存中的纯字节流,您可以使用 XmlTextReader 将此字节流作为 XML 进行分析。此内存流没有特别指定的编码。然后,该示例创建一个 XmlTextReader,分析该流并显示所得到的 XML。

function doClick(index, numTabs, id) {
document.all("tab" + id, index).className = "tab";
for (var i=1; i

td.code {
padding:0,10,0,10;
border-style:solid;
border-width:1;
border-bottom:0;
border-top:0;
border-right:0;
border-color:cccccc;
background-color:ffffee
}
td.tab {
text-align:center;
font:8pt verdana;
width:15%;
padding:3,3,3,3;
border-style:solid;
border-width:1;
border-right:0;
border-color:black;
background-color:eeeeee;
cursor:hand
}
td.backtab {
text-align:center;
font: 8pt verdana;
width:15%;
padding:3,3,3,3;
border-style:solid;
border-width:1;
border-right:0;
border-color:black;
background-color:cccccc;
cursor:hand
}
td.space {
width:70%;
font: 8pt verdana;
padding:0,0,0,0;
border-style:solid;
border-bottom:0;
border-right:0;
border-width:1;
border-color:cccccc;
border-left-color:black;
background-color:white
}

StringReader stream;
XmlTextReader reader = null;
try
{
Console.WriteLine ("Initializing StringReader ...");
stream = new StringReader("<?xml version='1.0'?>" +
"<!-- This file represents a fragment of a book store inventory database -->" +
"<bookstore>" +
" <book genre=\"autobiography\" publicationdate=\"1981\" ISBN=\"1-861003-11-0\">" +
"   <title>The Autobiography of Benjamin Franklin</title>" +
"   <author>" +
"       <first-name>Benjamin</first-name>" +
"       <last-name>Franklin</last-name>" +
"   </author>" +
"   <price>8.99</price>" +
" </book>" +
" <book genre=\"novel\" publicationdate=\"1967\" ISBN=\"0-201-63361-2\">" +
"   <title>The Confidence Man</title>" +
"   <author>" +
"       <first-name>Herman</first-name>" +
"       <last-name>Melville</last-name>" +
"   </author>" +
"   <price>11.99</price>" +
" </book>" +
"  <book genre=\"philosophy\" publicationdate=\"1991\" ISBN=\"1-861001-57-6\">" +
"   <title>The Gorgias</title>" +
"   <author>" +
"       <name>Plato</name>" +
"   </author>" +
"   <price>9.99</price>" +
" </book>" +
"</bookstore>");
// Load the XmlTextReader from the stream
reader = new XmlTextReader (stream);
Console.WriteLine ("Processing ...");
Console.WriteLine ();
FormatXml(reader);
}
catch (Exception e)
{
Console.WriteLine ("Exception: {0}", e.ToString());
}
finally
{
Console.WriteLine();
Console.WriteLine("Processing of stream complete.");
// Finished with XmlTextReader
if (reader != null)
reader.Close();
}

Dim stream as StringReader
Dim reader as XmlTextReader = nothing
try
Console.WriteLine ("Initializing StringReader ...")
stream = new StringReader ("<?xml version='1.0'?>" & _
"<!-- This file represents a fragment of a book store inventory database -->" & _
"<bookstore>" & _
" <book genre=""autobiography"" publicationdate=""1981"" ISBN=""1-861003-11-0"">" & _
"   <title>The Autobiography of Benjamin Franklin</title>" & _
"   <author>" & _
"       <first-name>Benjamin</first-name>" & _
"       <last-name>Franklin</last-name>" & _
"   </author>" & _
"   <price>8.99</price>" & _
" </book>" & _
" <book genre=""novel"" publicationdate=""1967"" ISBN=""0-201-63361-2"">" & _
"   <title>The Confidence Man</title>" & _
"   <author>" & _
"       <first-name>Herman</first-name>" & _
"       <last-name>Melville</last-name>" & _
"   </author>" & _
"   <price>11.99</price>" & _
" </book>" & _
"  <book genre=""philosophy"" publicationdate=""1991"" ISBN=""1-861001-57-6"">" & _
"   <title>The Gorgias</title>" & _
"   <author>" & _
"       <name>Plato</name>" & _
"   </author>" & _
"   <price>9.99</price>" & _
" </book>" & _
"</bookstore>")
' Load the XmlTextReader from the stream
reader = new XmlTextReader (stream)
Console.WriteLine ("Processing ...")
Console.WriteLine ()
FormatXml(reader)
catch e as Exception
Console.WriteLine ("Exception: {0} ", e.ToString())
finally
Console.WriteLine()
Console.WriteLine("Processing of stream complete.")
If Not reader Is Nothing
reader.Close()
end if
end try

C# VB
如果流是作为输入提供的,则 XmlTextReader 属性将对它进行解码,方法是将该流包括在 StreamReader 中,然后根据指定的 XML 编码调用 SwitchEncoding 属性。另外,XmlResolver 用于解析正确分析输入所需的外部资源,如文档类型定义 (DTD) 和架构。表示流的另一种方法是通过使用 StreamReader 类,该类实现读取字符流的读取器。下列代码示例说明加载名为 books.xml 的文件,然后使用 XmlTextReader 分析结果文件。

StreamReader streamreader = new StreamReader ("books.xml");
Console.WriteLine ("File books.xml read sucessfully ...");
// Load the XmlTextReader from the StreamReader
XmlTextReader xmlreader = new XmlTextReader (streamreader);

Dim streamreader As StreamReader = New StreamReader ("books.xml")
Console.WriteLine ("File books.xml read sucessfully ...")
' Load the XmlTextReader from the StreamReader
Dim xmlreader As XmlTextReader = New XmlTextReader (streamreader)

C# VB
此示例中的 FormalXml 方法显示在当前节点是元素节点的情况下,如何使用 MoveToNextAttribute 方法移到属性节点。这使您不但可以访问该节点的名称和值属性,而且由于此时处于节点上下文中,您还可以获取某些属性,如属性当前的命名空间。下列代码示例还显示 Format 方法,该方法此时显示当前节点的名称和值。

private static void FormatXml (XmlReader reader)
{
int piCount=0, docCount=0, commentCount=0, elementCount=0, attributeCount=0, textCount=0, whitespaceCount=0;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.ProcessingInstruction:
Format (reader, "ProcessingInstruction");
piCount++;
break;
case XmlNodeType.DocumentType:
Format (reader, "DocumentType");
docCount++;
break;
case XmlNodeType.Comment:
Format (reader, "Comment");
commentCount++;
break;
case XmlNodeType.Element:
Format (reader, "Element");
while(reader.MoveToNextAttribute())
{
Format (reader, "Attribute");
}
elementCount++;
if (reader.HasAttributes)
attributeCount += reader.AttributeCount;
break;
case XmlNodeType.Text:
Format (reader, "Text");
textCount++;
break;
case XmlNodeType.Whitespace:
whitespaceCount++;
break;
}
}
// Display the Statistics
Console.WriteLine ();
Console.WriteLine("Statistics for stream");
Console.WriteLine ();
Console.WriteLine("ProcessingInstruction: {0}",piCount++);
Console.WriteLine("DocumentType: {0}",docCount++);
Console.WriteLine("Comment: {0}",commentCount++);
Console.WriteLine("Element: {0}",elementCount++);
Console.WriteLine("Attribute: {0}",attributeCount++);
Console.WriteLine("Text: {0}",textCount++);
Console.WriteLine("Whitespace: {0}",whitespaceCount++);
}
// Format the output
private static void Format(XmlReader reader, String nodeType)
{
// Format the output
Console.Write(reader.Depth + " ");
Console.Write(reader.AttributeCount + " ");
for (int i=0; i < reader.Depth; i++)
{
Console.Write('\t');
}
Console.Write(nodeType + "<" + reader.Name + ">" + reader.Value);
Console.WriteLine();
}

private shared sub FormatXml (reader as XmlTextReader)
Dim piCount, docCount, commentCount, elementCount as Integer
Dim attributeCount, textCount, whitespaceCount as Integer
While reader.Read()
Select (reader.NodeType)
case XmlNodeType.ProcessingInstruction:
Format (reader, "ProcessingInstruction")
piCount += 1
case XmlNodeType.DocumentType:
Format (reader, "DocumentType")
docCount += 1
case XmlNodeType.Comment:
Format (reader, "Comment")
commentCount += 1
case XmlNodeType.Element:
Format (reader, "Element")
elementCount += 1
While reader.MoveToNextAttribute()
Format (reader, "Attribute")
end While
if (reader.HasAttributes)
attributeCount += reader.AttributeCount
end if
case XmlNodeType.Text:
Format (reader, "Text")
textCount += 1
case XmlNodeType.Whitespace:
whitespaceCount += 1
end Select
end While
' Display the Statistics for the file
Console.WriteLine ()
Console.WriteLine("Statistics for stream")
Console.WriteLine ()
Console.WriteLine("ProcessingInstruction: " & piCount)
Console.WriteLine("DocumentType: " & docCount)
Console.WriteLine("Comment: " & commentCount)
Console.WriteLine("Element: " & elementCount)
Console.WriteLine("Attribute: " & attributeCount)
Console.WriteLine("Text: " & textCount)
Console.WriteLine("Whitespace: " & whitespaceCount)
end sub
private shared sub Format(byref reader as XmlTextReader, nodeType as String)
' Format the output
Console.Write(reader.Depth & " ")
Console.Write(reader.AttributeCount & " ")
Dim i as Integer
for i = 0 to reader.Depth
Console.Write(Strings.chr(9))
Next
Console.Write(reader.Prefix & nodeType & "<" & reader.Name & ">" & reader.Value)
Console.WriteLine()
end sub

C# VB

摘要

流是作为数据的源或目标的输入或输出设备的抽象表示形式。
XmlTextReader 提供一些构造函数,用于从表示 URL 的字符串读取 XML,或从本地文件名、流或 TextReader 读取 XML。
XmlTextReader 提供从文件名、流或 TextReader 读取 XML 的构造函数。
可使用 MoveToNextAttribute 方法访问属性节点,该方法使您可以确定属性节点的属性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: