.NET c#Serialize to Parm名称和值

时间:2016-10-27 20:59:11

标签: c# xml serialization

我有以下对象:

public class sampleObj
{
    public string MemberId {get;set;}
    public string Address {get;set;}
}

我正在讨论的服务要求在<Parm/>元素的名称属性中定义属性名称,其值在一个子元素中。像这样的Xml元素:

<Parm Name="SampleObj">
  <Parm Name="MemberId">
    <Value>1234</Value>
  </Parm>
  <Parm Name="Address">
    <Value>xyz</Value>
  </Parm>
</Parm>

当我将sampleObj序列化为XML时,我得到以下不正确的XML:

<sampleObj>
  <MemberId>1234</MemberId>
  <Address>xyz</Address>
</sampleObj>

如何根据需要序列化对象?

2 个答案:

答案 0 :(得分:0)

你可以简单地使用Linq2Xml(我发现它在大多数时候都更容易使用)

var root = new XElement("Parm",
                new XAttribute("Name", "SampleObj"),
                new XElement("Parm",
                    new XAttribute("Name", "MemberId"),
                    new XElement("Value", "1234")
                ),
                new XElement("Parm",
                    new XAttribute("Name", "Address"),
                    new XElement("Value", "xyz")
                )
            );

var output = root.ToString();

<强>输出:

<Parm Name="SampleObj">
  <Parm Name="MemberId">
    <Value>1234</Value>
  </Parm>
  <Parm Name="Address">
    <Value>xyz</Value>
  </Parm>
</Parm>

答案 1 :(得分:0)

/// <summary>
/// When serialized, sampleObj is 'Parm' element
/// </summary>
[XmlRoot("Parm")]
public class sampleObj
{
    /// <summary>
    /// Name is an attribute of sampleObj/Parm
    /// </summary>
    [XmlAttribute("Name")]
    public string Name { get; set; }

    /// <summary>
    /// Value is an element of sampleObj/Parm
    /// </summary>
    [XmlElement("Value")]
    public string Value { get; set; }

    /// <summary>
    /// sampleObj has sampleObj list as elements
    /// </summary>
    [XmlElement("Parm")]
    public List<sampleObj> sampleObjs { get; set; }
}

产生结果:

<?xml version="1.0" encoding="utf-8"?>
<Parm Name="sampleObj">
  <Parm Name="MemberId">
    <Value>1234</Value>
  </Parm>
  <Parm Name="Address">
    <Value>xyz</Value>
  </Parm>
</Parm>

注意:

如有必要,还有其他步骤(使用XmlSerializer类)删除指令。