创建 XML 解析器的简单替代方案(而非 LINQ)





0/5 (0投票)
创建 LINQ 的一个简单的 XML 解析器替代方案。这里提供了一种简单的方法来解析 XML 字符串,并将它的元素名称和值存储在 Hashtable 中。
创建 XML 解析器的简单替代方案(而非 LINQ)
这里提供了一种简单的方法来解析 XML 字符串,并将它的元素名称和值存储在 Hashtable 中,你可以使用 GetAttribute() 方法通过键调用它。
public class Parse
{
Hashtable attributes;
public void ParseURL(string xmlData)
{
try
{
string errorString = string.Empty;
byte[] byteArray = new byte[xmlData.Length];
System.Text.ASCIIEncoding encoding = new
System.Text.ASCIIEncoding();
byteArray = encoding.GetBytes(xmlData);
attributes = new Hashtable();
// 加载内存流
MemoryStream memoryStream = new MemoryStream(byteArray);
memoryStream.Seek(0, SeekOrigin.Begin);
XmlTextReader reader = new XmlTextReader(memoryStream);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element
string strURI = reader.NamespaceURI;
string strName = reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (!attributes.ContainsKey(reader.Name))
{
attributes.Add(reader.Name, reader.Value);
}
}
}
break;
default
break;
}
}
}
catch (XmlException e)
{
Console.WriteLine("发生错误: " + e.Message);
}
}
public string GetAttribute(string key)
{
try
{
return attributes[key].ToString();
}
catch (XmlException e)
{
return "发生错误: " + e.Message;
}
}
}