0

I have classes, something like this:

Class1:
  List<Class2> A;
  string B;

Class2:
  Class3 A2;
  string B2;

Class3:
  string A3;
  string B3;

And I would like serialize it to XML, which will be looking like this:

<Class1>
  <Class2 A3="x" B3="y" B2="z" />
  <Class2 A3="x2" B3="y2" B2="z2" />
  ...
  <B> abc </B>
</Class1>

When I set in Class2 fields as XmlAttribute, I get unhandler exception System.InvalidOperationException
Is any way to do this? EDIT: Ok, I give to less details. I have problem how to serialize my own types list which will be look like up. I can serialize this to xml like:

<Class1>
  <A>
    <Class2 B2="x">
      <Class3 A3="x" B3="x"/>
    </Class2>
    <Class2 B2="x">
      <Class3 A3="x" B3="x"/>
    </Class2>
  </A>

But I would like have class3 as attribute without name class 3 (only fields from this class) and I don't want have to list, only listed elements have name Class2. I'm not sure it's understandable...

heheszki
  • 35
  • 10
  • I guess the exception had a message and even may be an inner exception. can you post it? To serialize class members they have to be public! very important. – Mong Zhu Aug 08 '17 at 13:11
  • Possible duplicate of [Serialize Property as Xml Attribute in Element](https://stackoverflow.com/questions/11330643/serialize-property-as-xml-attribute-in-element) – Mong Zhu Aug 08 '17 at 13:12
  • I edit my question and add some details. – heheszki Aug 08 '17 at 13:24
  • I guess you will have to build it by hand using [XElement](https://msdn.microsoft.com/en-us/library/system.xml.linq.xelement(v=vs.110).aspx) – Mong Zhu Aug 08 '17 at 13:32
  • 1
    Or quick and dirty add `XmlIgnore` to the `Class3` property and reflect the child properties in `Class2`. But that is really just a quick and dirty way of doing it. – Adwaenyth Aug 08 '17 at 13:34

1 Answers1

0

Can you move A3 and B3 props to Class2?

Class1:
 [XmlElement("Class2")]
 List<Class2> A;
 [XmlElement]
 string B;

Class2:
 [XmlAttribute]
 string A3;
 [XmlAttribute]
 string B3;
 [XmlAttribute]
 string B2;
Paweł
  • 133
  • 2
  • 11