0

I'm serializing a structure that results in this output:

<NachrichtenKonfiguration>
  <Elemente>
    <Element>
      <Typ>Bool</Typ>
      <Bezeichnung>Gut</Bezeichnung>
    </Element>
    <Element>
      <Typ>Int</Typ>
      <Bezeichnung>Dauer</Bezeichnung>
    </Element>
  </Elemente>
  <Name>Teiledaten</Name>
</NachrichtenKonfiguration>

And I would like it to be rather like this:

<NachrichtenKonfiguration Name="Teiledaten">
  <Elemente>
    <Element Typ="Bool" Bezeichnung="Gut"/>
    <Element Typ="Int" Bezeichnung="Schleifdauer"/>
  </Elemente>
</NachrichtenKonfiguration>

Is it possible to make XmlSerialzer / XmlWriter do that (Use attributes instead of nested elements)?

Greetings,

Tim

Ravior
  • 561
  • 2
  • 9
  • 30
  • 4
    Yes, it is possible. Did you try anything at all? – Khalil Khalaf Sep 22 '16 at 12:27
  • 3
    Possible duplicate of [How to serialize an XmlDocument to a well-formatted human-readable XML?](http://stackoverflow.com/questions/17101817/how-to-serialize-an-xmldocument-to-a-well-formatted-human-readable-xml) – James Gould Sep 22 '16 at 12:31
  • 2
    @JayGould He is not looking for Identation. He is looking for a code that adds attributes for an element rather than nested elements for an element. – Khalil Khalaf Sep 22 '16 at 12:32
  • @ Jay Gould: No itts not a duplicate of that thread, I already have the indention, I just wanted to know how to correctly format attributes in xml. – Ravior Sep 22 '16 at 12:33

1 Answers1

2

Ok I got it, you simply need to add the [XmlAttribute]-tag over the corresponding declaration.

Here's how. If you have a class called "Person" and you have two attributes in it, write the code like this:

[Serializable]
public class Person
{
    [XmlAttribute]
    public int Age;
    [XmlAttribute]
    public string Name;

    public Person()
    {

    }
}

When serializing (with XmlWriter settings set to indent lines) above structure results in this xml code:

<Person Age="21" Name="Stacky" />
Ravior
  • 561
  • 2
  • 9
  • 30