Guille
Guille

Reputation: 115

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?

Upvotes: 2

Views: 140

Answers (2)

Erik
Erik

Reputation: 12868

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.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

Use XmlText attribute:

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

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

Upvotes: 4

Related Questions