简体   繁体   中英

c# serialize to xml my own type as attribute

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM