0

I used xsd.exe to generate a cs file from my xsd file. I have an element that can have a null value. When I serialize the class the property disappears if it's null, if I set IsNullable = true, it shows the property but with nil attibutes, is there a way modify the cs file generated by xsd.exe to show the empty tag without attributes?

[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable = true)]
public string Phone {
    get { return this.phoneField; }
    set { this.phoneField = value; }
}

if Phone = null and IsNullable = true, I get

<Phone p7:nil="true" xmlns:p7="some namespace" />

if Phone = null and IsNullable = false, Phone doesn't even show up on my xml file.

Desired output

<Phone />
  • Phone is a string and should never contain attributes like what you posted. What you posted is not accurate. – jdweng Jul 10 '21 at 08:11
  • You need to return an empty string instead of null: `get { return this.phoneField ?? ""; }`. `` is how an empty string gets serialized so if that is what you want for a null string, you will be unable to distinguish between null and empty strings when round-tripping. [XmlSerializer that treats null values as empty elements](https://stackoverflow.com/q/47797890/3744182) is unanswered; I don't think there is any way to get what you want purely through attributes. – dbc Jul 11 '21 at 00:24
  • You could do tricks with a subclassed `XmlWriter` though as shown in https://dotnetfiddle.net/0e9AWe. – dbc Jul 11 '21 at 00:25
  • @dbc answer `get { return this.phoneField ?? ""; }` worked! Thanks! – user16318579 Jul 12 '21 at 17:22

0 Answers0