小编典典

将对象序列化为 XML

all

我有一个继承的 C# 类。我已经成功地“构建”了对象。但我需要将对象序列化为 XML。有没有简单的方法来做到这一点?

看起来该类已设置为进行序列化,但我不确定如何获取 XML 表示。我的类定义如下所示:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
  ...
}

这是我认为我可以做的,但它不起作用:

MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();

如何获取此对象的 XML 表示?


阅读 83

收藏
2022-04-14

共1个答案

小编典典

您必须使用 XmlSerializer 进行 XML 序列化。下面是一个示例片段。

 XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
 var subReq = new MyObject();
 var xml = "";

 using(var sww = new StringWriter())
 {
     using(XmlWriter writer = XmlWriter.Create(sww))
     {
         xsSubmit.Serialize(writer, subReq);
         xml = sww.ToString(); // Your XML
     }
 }

根据@kiquenet 对泛型类的请求:

public class MySerializer<T> where T : class
{
    public static string Serialize(T obj)
    {
        XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
        using (var sww = new StringWriter())
        {
            using (XmlTextWriter writer = new XmlTextWriter(sww) { Formatting = Formatting.Indented })
            {
                xsSubmit.Serialize(writer, obj);
                return sww.ToString();
            }
        }
    }
}

用法:

string xmlMessage = MySerializer<MyClass>.Serialize(myObj);
2022-04-14