Reputation: 65
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 ?
Upvotes: 3
Views: 2463
Reputation: 666
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!
Upvotes: 0
Reputation: 7144
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?
Upvotes: -1
Reputation: 292345
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.
Upvotes: 2