MVC 4.0 - Xml to model
本文关键字:to model Xml MVC | 更新日期: 2023-09-27 18:11:28
我有一个返回xml的系统,我需要构建一些使用这些数据的MVC页面。我使用MVC 4.0和c# FW4.0。我像这样填充我的模型:
List<PersonName> tmpList = new List<PersonName>();
IEnumerable<PersonName> PeopleNames = tmpList;
XDocument oDoc = XDocument.Parse(sResponse);
var vPeopleNames = from c in oDoc.Descendants("PersonName")
select new PersonName()
{
PersonID = (string)c.Element("PersonID"),
FirstName = (string)c.Element("FirstName"),
LastName = (string)c.Element("LastName")
};
PeopleNames = vPeopleNames;
var oModel = PeopleNames;
return View("PeopleNamesList", PeopleNames);
我想知道是否有一种方法可以自动做到这一点。我不想指定"PersonID"、"FirstName"answers"LastName"字段的名称。如果我有50个字段,这将是太痛苦了…
可以借助XNode.CreateReader()
和XContainer.CreateWriter()
从XmlSerializer
序列化到XElement
。以下扩展方法可以完成这项工作:
public static class XObjectExtensions
{
public static T Deserialize<T>(this XContainer element, XmlSerializer serializer = null)
{
using (var reader = element.CreateReader())
{
object result = (serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
if (result is T)
return (T)result;
}
return default(T);
}
public static XmlSerializerNamespaces NoStandardXmlNamespaces()
{
var ns = new XmlSerializerNamespaces();
ns.Add("", ""); // Disable the xmlns:xsi and xmlns:xsd attributes.
return ns;
}
public static XElement SerializeToXElement<T>(this T obj)
{
return obj.SerializeToXElement(null, NoStandardXmlNamespaces()); // Disable the xmlns:xsi and xmlns:xsd attributes by default.
}
public static XElement SerializeToXElement<T>(this T obj, XmlSerializerNamespaces ns)
{
return obj.SerializeToXElement(null, ns);
}
public static XElement SerializeToXElement<T>(this T obj, XmlSerializer serializer, bool omitStandardNamespaces)
{
return obj.SerializeToXElement(serializer, (omitStandardNamespaces ? NoStandardXmlNamespaces() : null));
}
public static XElement SerializeToXElement<T>(this T obj, XmlSerializer serializer, XmlSerializerNamespaces ns)
{
var doc = new XDocument();
using (var writer = doc.CreateWriter())
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(writer, obj, ns);
var element = doc.Root;
if (element != null)
element.Remove();
return element;
}
}
然后像这样使用:
var vPeopleNames = (from c in oDoc.Descendants("PersonName")
select c.Deserialize<PersonName>()).ToList();
var peopleXml = vPeopleNames.SerializeToXElement(); // Creates a root element named <ArrayOfPersonName> containing all people names as child elements.
PersonName
类定义如下:
public class PersonName
{
public string PersonID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}