5

我有以下 C# 类

[XmlRoot("Customer")]
public class MyClass
{
    [XmlElement("CustId")]
    public int Id {get;set;}

    [XmlElement("CustName")]
    public string Name {get;set;}
}

然后我使用以下函数将类对象序列化为 XML

 public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
 {
    XmlSerializer serializer = 
          new XmlSerializer(obj.GetType(), new XmlRootAttribute("Response"));

    using (MemoryStream ms = new MemoryStream())
    {
       XmlDocument xmlDoc = new XmlDocument();
       serializer.Serialize(ms, obj);
       ms.Position = 0;
       xmlDoc.Load(ms);
    }
}

我当前对 XML 的输出是这样的;

<Response>
  <CustId></CustId>
  <CustName></CustName>
</Response>

但是我怎样才能得到这样的响应;

<Response>
  <Customer>
     <CustId></CustId>
     <CustName></CustName>
  </Customer>
</Response>
4

3 回答 3

10

XmlElementAttributeon (根据http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute(v=vs.110).aspxMyClass在此处实际上无效)更改为:XmlTypeAttribute

    [XmlType("Customer")]
    public class MyClass
    {
        [XmlElement("CustId")]
        public int Id { get; set; }

        [XmlElement("CustName")]
        public string Name { get; set; }
    }

序列化方法现在可以是(与问题中的方法相同,但在构造函数中没有第二个参数XmlSerializer):

    public static XmlDocument SerializeObjectToXML(object obj, string sElementName)
    {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        XmlDocument xmlDoc = new XmlDocument();
        using (MemoryStream ms = new MemoryStream())
        {

            serializer.Serialize(ms, obj);
            ms.Position = 0;
            xmlDoc.Load(ms);
        }

        return xmlDoc;
    }
于 2013-11-08T12:02:18.143 回答
4

您可以创建一个包含您的客户的响应对象,因为这也是您想要的 xml 显示的内容。

[XmlRoot("Response")] 
public class ResponseClass
{
  [XmlElement("Customer")]
  public Myclass Customer {get;set;}
}
于 2013-11-08T12:00:16.927 回答
2

你可以这样定义它们:

public class MyClass
{
    [XmlElement("Customer")]
    public Customer cust { get; set; } 

}
public class Customer
{
    [XmlElement("CustId")]
    public int Id { get; set; }

    [XmlElement("CustName")]
    public string Name { get; set; }
}

顺便说一句,[XmlElement("Customer")]在您的示例中无效...

于 2013-11-08T12:09:43.480 回答