简体   繁体   中英

C# xml serialization

I'm serializing an object to xml in c# and I would like to serialize

public String Marker { get; set; }

into

<Marker></Marker>

when string Marker has no value.

Now I get

<Marker />

for Marker == string.Empty and no Marker node for null . How can I get this?

You can easily suppress the <Marker> element if the Marker property is null. Just add a ShouldSerializeMarker() method:

public bool ShouldSerializeMarker()
{
    return Marker != null;
}

It will be called automatically by XmlSerializer to decide whether or not to include the element in the output.

As for using the expanded form of the <Marker> element when the string is empty, there's no easy way to do it (you could probably write your own XmlWriter , but it would be a pain). But anyway it doesn't make sense, because <Marker /> and <Marker></Marker> have exactly the same meaning.

If you want to have the closing tags you have to change the implementation of your xml structure; as far as I understand this topic of serialization separate closing tags are only produced if you are serializing a 'complex' object (eg: a class) and not a 'simple' object (eg: a string).

An example would be:

[XmlRoot]
public class ClassToSerialize
{
  private StringWithOpenAndClosingNodeClass mStringWithOpenAndClosingNode;

  [XmlElement]
  public StringWithOpenAndClosingNodeClass Marker
  {
    get { return mStringWithOpenAndClosingNode ?? new StringWithOpenAndClosingNodeClass(); }
    set { mStringWithOpenAndClosingNode = value; }
  }
}

[XmlRoot]
public class StringWithOpenAndClosingNodeClass
{
  private string mValue;

  [XmlText]
  public string Value
  {
    get { return mValue ?? string.Empty; }
    set { mValue = value; }
  }
}

If you serialize this object to XML you'll get:

<ClassToSerialize><Marker></Marker></ClassToSerialize>

I hope this helps!

You can use the IsNullable property of the XMLElementAttribute to configure the XmlSerializer to generate XML for your null value.

Haven't figured out how to produce an opening and closing elements for an element with no value, though. What you have already is perfectly legal XML. That is,

<Marker></Marker> 

is the same as

<Marker/>

Do you really need both opening and closing tags?

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