xml是一层结构不涉及嵌套节点时, 转换为Hashtable对象去操作数据会更便捷
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ToolDemo
{
class Program
{
static void Main(string[] args)
{
string xml = @"
<xml>
<UserName><![CDATA[Administrator]]></UserName>
<Age><![CDATA[18]]></Age>
</xml>";
Hashtable ht = XmlToHashtable(xml);
Console.WriteLine("UserName: {0}", (string)ht["UserName"]);
Console.WriteLine("Age: {0}", (string)ht["Age"]);
/*
运行结果
UserName: Administrator
Age: 18
*/
Console.Read();
}
/// <summary>
/// 将Xml文本转换成Hashtable
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static Hashtable XmlToHashtable(string xml)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNode xmlNode = xmlDoc.ChildNodes[0];
Hashtable ht = new Hashtable();
if (xmlNode.ChildNodes.Count > 0)
{
foreach (XmlNode xn in xmlNode.ChildNodes)
{
ht.Add(xn.Name, xn.InnerText);
}
}
return ht;
}
/// <summary>
/// 将Xml对象转换成Hashtable
/// </summary>
/// <param name="xmlDoc"></param>
/// <returns></returns>
public static Hashtable XmlToHashtable(XmlDocument xmlDoc)
{
XmlNode xmlNode = xmlDoc.ChildNodes[0];
Hashtable ht = new Hashtable();
if (xmlNode.ChildNodes.Count > 0)
{
foreach (XmlNode xn in xmlNode.ChildNodes)
{
ht.Add(xn.Name, xn.InnerText);
}
}
return ht;
}
}
}