Is it possible to serialize an array so that its elements are not wrapped with a tag for the array?

I have the following classes Ruleand Ruleset:

[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; }
}

(I hope everything is fine with me - this is a radically simplified example, not the actual code.) They serialize like this:

<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>

Additional tags <Rules>and <Operands>in my opinion a rather ugly, and they degrade readability. Is there any way to fix them?

Like this:

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

Try the following:

[XmlElement("Rule")]
public Rule[] Rules {
+3
source

I think you will need to manipulate the XML with your self before / after converting it to Object / XML.

But think about what you are trying to do.

. , , .

. , /.

:

<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 .

+1

Source: https://habr.com/ru/post/1782324/


All Articles