C# xml serialization

拟墨画扇 提交于 2019-12-12 15:15:47

问题


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 ?


回答1:


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.




回答2:


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!




回答3:


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?



来源:https://stackoverflow.com/questions/5817160/c-sharp-xml-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!