1

In C# is it possible to serialize empty string as nil value. Let's take the object like this:

var myBook = new Book(){ Author = "John S.", ISBN = null };

I'd like to have:

<Book>
  <Author>John S.</Author>
  <ISBN nil="true"/>
</Book>

Is it possible to achieve such a result with one of third party xml serializers like ExtendedXmlSerializer or YAXLib?

Regards.

0

1 Answer 1

3

You can try this :

var myBook = new Book() { Author = "John S.", ISBN = null };
XmlSerializer xs = new XmlSerializer(typeof(Book));
StringWriter sw = new StringWriter();
xs.Serialize(sw, myBook);
Console.WriteLine(sw.ToString() );

Also you need to add an attribute :

public class Book
{
    public string Author { get; set; }
    [System.Xml.Serialization.XmlElement(IsNullable = true)]
    public string ISBN { get; set; }
}

Result :

<?xml version="1.0" encoding="utf-16"?>
<Book xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Author>John S.</Author>
  <ISBN xsi:nil="true" />
</Book>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.