我继承了一个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表示形式?


当前回答

现在可能太晚了,但是只有用户定义的命名空间是序列化的:

public static string XmlSerialize<T>(this T obj) where T : class
        {
            Type serialType = typeof(T);
            var xsSubmit = new XmlSerializer(serialType);

            XmlWriterSettings xws = new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true };
            

            var Namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {           
            new XmlQualifiedName(string.Empty,  GetXmlNameSpace(serialType) ?? string.Empty )


        });
 private static string GetXmlNameSpace(Type target)
        {
            XmlRootAttribute attribute = (XmlRootAttribute)Attribute.GetCustomAttribute(target, typeof(XmlRootAttribute));
            return attribute == null ? null : attribute.Namespace;
        }

并在自定义类中定义命名空间

 [XmlRoot("IdentityTerminal",Namespace = "http://my-name-space/XMLSchema")]
   
    public class IdentityTerminal
    {
    }

这段代码允许只使用用户定义的名称空间,而忽略默认的名称空间。

其他回答

您可以使用如下函数从任何对象获取序列化的XML。

public static bool Serialize<T>(T value, ref string serializeXml)
{
    if (value == null)
    {
        return false;
    }
    try
    {
        XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        XmlWriter writer = XmlWriter.Create(stringWriter);

        xmlserializer.Serialize(writer, value);

        serializeXml = stringWriter.ToString();

        writer.Close();
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

你可以从客户端调用它。

public string ObjectToXML(object input)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(input.GetType());
        serializer.Serialize(stringwriter, input);
        return stringwriter.ToString();
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null)
            ex = ex.InnerException;

        return "Could not convert: " + ex.Message;
    }
}

//Usage
var res = ObjectToXML(obj)

您需要使用以下类:

using System.IO;
using System.Xml;
using System.Xml.Serialization;

下面是一个基本代码,可以帮助将c#对象序列化为xml:

using System;

public class clsPerson
{
  public  string FirstName;
  public  string MI;
  public  string LastName;
}

class class1
{ 
   static void Main(string[] args)
   {
      clsPerson p=new clsPerson();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(Console.Out, p);
      Console.WriteLine();
      Console.ReadLine();
   }
}    

这比调用类的ToString方法要复杂一些,但也不是很复杂。

下面是一个简单的下拉函数,可以用来序列化任何类型的对象。它返回一个包含序列化XML内容的字符串:

public string SerializeObject(object obj)
{
    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
        serializer.Serialize(ms, obj);
        ms.Position = 0;
        xmlDoc.Load(ms);
        return xmlDoc.InnerXml;
    }
}

这里有一个关于如何做到这一点的很好的教程

基本上应该使用System.Xml.Serialization.XmlSerializer类来做到这一点。