大伙看看这个xml怎么转为对象?
<result>
<list>
<user name="Name">.net</user>
<user name="No">123</user>
<user name="Married">true</user>
</list>
<list>
<user name="Name">ruby</user>
<user name="No">123</user>
<user name="Married">false</user>
</list>
</result>
string xml = @"<result>
<list>
<user name=""Name"">.net</user>
<user name=""No"">123</user>
<user name=""Married"">true</user>
</list>
<list>
<user name=""Name"">ruby</user>
<user name=""No"">123</user>
<user name=""Married"">false</user>
</list>
</result>";
ResultModel result = XmlUtil.ReadFromXml<ResultModel>(xml);
public static T ReadFromXml<T>(string xml)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
nameSpaces.Add("", "");
object ext = null;
try
{
using (TextReader reader = new StringReader(xml))
{
ext = serializer.Deserialize(reader);
reader.Close();
}
}
catch
{
ext = null;
}
return (T)ext;
}
[XmlRoot("result")]
public class ResultModel
{
[XmlElement("list")]
public List<UserCollectionModel> List
{
get;
set;
}
}
public class UserCollectionModel
{
[XmlElement("user")]
public List<UserModel> User
{
get;
set;
}
}
public class UserModel
{
[XmlAttribute("name")]
public string Name
{
get;
set;
}
[XmlText]
public string Text
{
get;
set;
}
}