将对象模型转换为XML

时间:2014-04-16 05:28:07

标签: c# xml asp.net-mvc-4

大家好,我怎样才能将对象模型转换为xmldocument。这是我的目标:

var profile = new ProfileModel() 
                { 
                    xh="aa",
                    FirstName = "wolverine",
                    LastName = "wolverine2",
                    PhoneNumber = "66332214477",
                    Email = "wolverine@wolverine.com",
                    SourceSystem = "TY",
                    ID = "ty1002224"
                };

现在我正在手动这样做:

XDocument doc = new XDocument(new XElement("aa",
                                            new XElement("FirstName","wolverine2"),
                                            new XElement("LastName", "wolverine"),
                                            new XElement("PhoneNumber", "66332214477"),
                                            new XElement("Email", "wolverine@wolverine.com"),
                                            new XElement("SourceSystem", "TY"),
                                            new XElement("ID", "ty1002224")
                                            ));

但是我想要更通用的东西,所以我可以将它用于我的所有对象。另外,我有一个案例,我有一个ProfileModel列表,需要将其转换为xmldocument。

编辑: 我希望输出是纯xdocument:

<aa>
  <FirstName>wolverine2</FirstName>
  <LastName>wolverine</LastName>
  <PhoneNumber>66332214477</PhoneNumber>
  <Email>wolverine@wolverine.com</Email>
  <SourceSystem>TY</SourceSystem>
  <ID>ty1002224</ID>
</aa>

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

使用惊人的XDocument类。这将使用反射并序列化所有属性。

// in System.Xml.Linq
XDocument doc = new XDocument();
using (var writer = doc.CreateWriter())
{
    // write xml into the writer
    var serializer = new DataContractSerializer(objToSerialize.GetType());
    serializer.WriteObject(writer, objectToSerialize);
}
Console.WriteLine(doc.ToString());

来源:How do I serialize an object into an XDocument?