大家好,我怎样才能将对象模型转换为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>
答案 0 :(得分:3)
查看XmlSerializer类
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
答案 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());