是否可以序列化数组,使其元素不包含在数组的标记中?

时间:2010-12-27 17:08:35

标签: c# serialization xml-serialization

我有以下RuleRuleset类:

[XmlInclude(typeof(OrRule))]
[XmlInclude(typeof(AndRule))]
[XmlInclude(typeof(EmptyRule))]
[XmlInclude(typeof(MatchRule))]
public class Rule {}

[XmlType("Or")]
public class OrRule
{
    public Rule[] Operands { get; set; }
}

[XmlType("And")]
public class AndRule
{
    public Rule[] Operands { get; set; }
}

[XmlType("Empty")]
public class EmptyRule {}

[XmlType("Match")]
public class MatchRule
{
    public string Regex { get; set; }
}

public class Ruleset
{
    public string Name { get; set; }

    [XmlArrayElement(typeof(OrRule))]
    [XmlArrayElement(typeof(AndRule))]
    [XmlArrayElement(typeof(EmptyRule))]
    [XmlArrayElement(typeof(MatchRule))]
    public Rule[] Rules { get; set; }
}

(我希望我把一切都搞定了 - 这是一个根本简化的例子,而不是实际的代码。)这些被序列化为这样:

<Ruleset Name="PasswordEmptyAllowed">
  <Rules>
    <Or>
      <Operands>
        <Empty />
        <And>
          <Operands>
            <Match Regex="\d" />
            <Match Regex="[a-záéíóöőúüű]" />              
            <Match Regex="[A-ZÁÉÍÓÖŐÚÜŰ]" />
          </Operands>
        </And>
      </Operands>
    </Or>
  </Rules>
</Ruleset>

我认为额外的<Rules><Operands>标签非常难看,并且会损害可读性。有没有办法消除它们?

像这样:

<Ruleset Name="PasswordEmptyAllowed">
  <Or>
    <Empty />
    <And>
      <Match Regex="\d" />
      <Match Regex="[a-záéíóöőúüű]" />              
      <Match Regex="[A-ZÁÉÍÓÖŐÚÜŰ]" />
    </And>
  </Or>
</Ruleset>

2 个答案:

答案 0 :(得分:3)

试试这个:

[XmlElement("Rule")]
public Rule[] Rules {

答案 1 :(得分:1)

我认为你必须在转换为Object / XML之前/之后操纵XML。

但想想你想要做什么。

我想在标签丑陋上与你意见不一致。我认为它们有助于提高可读性,它们将儿童标签保持在一起。

想象一个带有两个这样的集合的标签,没有包装标签。使用您的方法,它们可以很容易地混合在一起,使得它们更难以阅读和序列化/反序列化。

实施例

<And>
  <Match Regex="\d" />
  <Replace From="123" To="ABC" />
  <Match Regex="[a-záéíóöőúüű]" />              
  <Replace From="_" To=" " />
  <Match Regex="[A-ZÁÉÍÓÖŐÚÜŰ]" />
  <Replace From="-" To="#" />
</And>

而不是

<And>
  <Matches>
      <Match Regex="\d" />
      <Match Regex="[a-záéíóöőúüű]" />              
      <Match Regex="[A-ZÁÉÍÓÖŐÚÜŰ]" />
  </Matches>
  <Replaces>
      <Replace From="123" To="ABC" />      
      <Replace From="_" To=" " />
      <Replace From="-" To="#" />
  </Replaces>
</And>

您决定哪一个是可读和可维护的。

考虑一下您建议的方法可能出现的问题,以及XmlSerializer.Net Framework促进当前实施的原因。