以下类为直接把XML结构数据转换成Object形式
调用规则为:
如:
public class bookInfo
{
public string title
{
get;
set;
}
public string author
{
get;
set;
}
public string price
{
get;
set;
}
public string id
{
get;
set;
}
}
class Program
{
static void Main(string[] args)
{
string text = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><bookstore><book id=\"hami\"><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 id=\"vv\"><title>The Confidence Man</title><author><first-name>Herman</first-name><last-name>Melville</last-name></author><price>11.99</price></book></bookstore>";
IList<bookInfo> list= XmlHelper.GetList<bookInfo>(text, "/bookstore/book");
foreach (bookInfo info in list)
{
Console.WriteLine("book id={0},price={1},author={2},title={3}",info.id,info.price,info.author,info.title);
}
Console.Read();
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.XPath;
using System.Reflection;
namespace TestXmlHelper
{
public class XmlHelper
{
/// <summary>
/// 创建XML浏览
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static XPathNavigator GetXPathNavigator(ref string text)
{
//byte[] bt=Encoding.UTF8.GetBytes(text);
//MemoryStream ms=new MemoryStream(bt);
TextReader read = new StringReader(text);
XPathDocument doc = new XPathDocument(read);
return doc.CreateNavigator();
}
/// <summary>
/// 获取某个XML中的Path中的model(T)列表,此结构为子标签形式如:<tag id='' attr=''><a></a><b></b><c></c></tag>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text"></param>
/// <param name="path"></param>
/// <returns></returns>
public static IList<T> GetList<T>(string text, string path) where T : new()
{
Type type = typeof(T);
PropertyInfo[] ps = type.GetProperties();
IList<T> list = new List<T>();
XPathNavigator pn = GetXPathNavigator(ref text);
XPathNodeIterator iter = pn.Select(path);
if (iter.Count > 0)
{
int i = 0;
while (iter.MoveNext())
{
i++;
T t = new T();
foreach (PropertyInfo info in ps)
{
string name = info.Name;
string attrValue=null;
string v = iter.Current.GetAttribute(name, string.Empty);
//获取属性
if (v!=string.Empty)
{
attrValue = v;
}
else
{//获取子标签
XPathNavigator xpn = iter.Current.SelectSingleNode(name);
if (xpn != null)
{
attrValue=xpn.Value;
}
}
//非空时,进行赋值
if (attrValue != null)
{
Type pType = info.PropertyType;
object obj = Convert.ChangeType(attrValue, pType);
info.SetValue(t, obj, null);
}
}
list.Add(t);
}
}
return list;
}
}
}

