简体   繁体   中英

serialize class to xml

I'm trying to serialize an object (class) to Xml, because I need to send it to JDE Business Function. I have problems when I need to represent an arraylist like this:

<params>
<param name='szGroup'>val1</param>
<param name='szOWPassword'>val2</param>
...
</params>

In my class I created this:

...
[XmlArray("params")]
[XmlArrayItem("param")]
public List<Param> Param {get; set;}
...

public class Param
{
    [XmlAttribute("name")]
    public string Name { get; set; }
}

But I get this:

<params>
  <param name="szGroup" />
  <param name="szOWPassword" />...

Anyone can help me with this?

Use XmlText attribute:

public class Param
{
    [XmlAttribute("name")]
    public string Name { get; set; }

    [XmlText]
    public string Value { get; set; }
}

Depending on how you need to serialize, it may be wise to subclass XmlTextWriter in your case to have more control over the serialization. If you must have the full ending elements, this is one of the easiest ways to accomplish that:

public class MyXmlTextWriter : XmlTextWriter
{
  public MyXmlTextWriter(TextWriter writer) : base(writer) { }

  public override void WriteEndElement()
  {
    base.WriteFullEndElement();
  }

  // Override any additional XML serialization methods.
}

Then you would just instantiate MyXmlTextWriter instead and use it to serialize your XML.

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