如何使用 XmlReader 分析 XML
Silverlight
本主题提供两个如何使用 XmlReader 来分析 Microsoft .NET Framework for Silverlight 中的 XML 流的示例。
有关如何使用 XmlReader 分析 XML 的更多示例,请参见 .NET Framework 文档中的以下主题:
Current Node Position in XmlReader(XmlReader 中的当前节点位置)
Reading Elements(读取元素)
Reading Attributes(读取属性)
Reading Content(读取内容)
配置 Silverlight Visual Studio 项目以运行此示例
1.
修改 page.xaml 文件,使它包含下面的 TextBlock 元素:
复制
<TextBlock x:Name ="OutputTextBlock" Canvas.Top ="10" TextWrapping="Wrap"/>
2.
在应用程序的 page.xaml.cs(在 Visual Basic 中为 page.xaml.vb)源文件中,添加下面的 using 语句(在 Visual Basic 中为 Imports):
using System.Xml;
using System.IO;
using System.Text;
示例
--------------------------------------------------------------------------------
下面的示例在流中导航以确定当前节点类型,然后使用 XmlWriter 输出 XmlReader 内容
StringBuilder output = new StringBuilder();
String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Items>
<Item>test with a child element <more/> stuff</Item>
</Items>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(output, ws))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
OutputTextBlock.Text = output.ToString();
下面的示例使用 XmlReader 方法读取元素和属性的内容。
StringBuilder output = new StringBuilder();
String xmlString =
@"<bookstore>
<book genre='autobiography' publicationdate='1981-03-22' 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>
</bookstore>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("book");
reader.MoveToFirstAttribute();
string genre = reader.Value;
output.AppendLine("The genre value: " + genre);
reader.ReadToFollowing("title");
output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
}
OutputTextBlock.Text = output.ToString();
一段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
namespace XMLReader
{
public class XMLReader
{
User user = null;
UserCredit credit = null;
public string ReaderAttribute(string name)
{
string contents = null;
using (XmlReader reader = XmlReader.Create(name))
{
if (reader.HasAttributes)
{
switch (reader.NodeType)
{
case XmlNodeType.Element: contents+=(reader.Name); break;
case XmlNodeType.Text:contents+=":" + reader.Value + ";"; break;
}
}
}
return contents;
}
public string ReadXml(string xml)
{
StringBuilder builder = new StringBuilder();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
while (reader.Read())
{
if (reader.HasValue)//这样把没值的数据屏蔽,如User
{
switch (reader.NodeType)
{
case XmlNodeType.Element: builder.Append(reader.Name); break;
case XmlNodeType.Text: builder.Append("=" + reader.Value + ";"); break;
}
}
}
}
return builder.ToString();
}
public IDictionary<string, string> GetDic(string content)
{
IDictionary<string, string> dit = new Dictionary<string, string>();
string[] arrays = content.Split(';');
foreach (string item in arrays)
{
string[] param = item.Split('=');
if (!string.IsNullOrEmpty(param[0]) && !string.IsNullOrEmpty (param[1]))//注意:必须key值和Value值都存在才可加入
{
dit.Add(param[0], param[1]);
}
}
return dit;
}
public User GetUser(IDictionary<string, string> dit)
{
user = new User();
credit = new UserCredit();
IEnumerator<KeyValuePair<string, string>> dem = dit.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
switch (name)
{
case "user_id": user.UserId = Convert.ToInt64(value); break;
case "type": user.Type = value; break;
case "sex": user.Sex = value; break;
case "nick": user.Nick = value; break;
case "created": user.Created = value; break;
case "total_num": credit.TotalNum = Convert.ToInt64(value); break;
case "score": credit.Score = Convert.ToInt64(value); break;
default: break;
}
}
return user;
}
public User GETUser(IDictionary<string, string> dit)
{
user = new User();
credit = new UserCredit();
Dictionary<string, string> dic = new Dictionary<string, string>(dit.Count);
foreach (KeyValuePair<string, string> kvp in dic)
{
string name = kvp.Key;
switch (name)
{
case "type": user.Type = kvp.Value ; break;
case "sex": user.Sex = kvp.Value; break;
case "nick": user.Nick = kvp.Value; break;
case "created": user.Created =kvp.Value; break;
default: break;
}
}
return user;
}
public string Test(IDictionary<string, string> dit)
{
string KV = null;
Dictionary<string, string> dic = new Dictionary<string, string>(dit.Count);
foreach (var item in dic)//注意:值为空的情况
{
KV +="键:"+ item.Key + "值:"+item.Value;
}
//foreach (var value in dic.Values)
//{
// KV += "值的集合:" + value;
//}
return KV;
}
}
}