将对象序列化为XML时,表示Null值的方式不同
我使用以下代码将对象序列化为XML:
using System.IO; using System.Xml.Serialization; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { MyClass thisClass = new MyClass() { One = "Foo", Two = string.Empty, Three = "Bar" }; Serialize(thisClass, @"C:\Users\JMK\Desktop\x.xml"); } static void Serialize(T x, string fileName) { XmlSerializer v = new XmlSerializer(typeof(T)); TextWriter f = new StreamWriter(fileName); v.Serialize(f, x); f.Close(); } } public class MyClass { public string One { get; set; } public string Two { get; set; } public string Three { get; set; } } }
这导致以下XML:
Foo Bar
除了一件事,这一切都很好。 如果我的一个值为null,我不能在XML中省略它,它需要在那里,我不能将它表示为 ,而是我需要将其表示为
。
这可能使用我目前的方法吗?
运用
[XmlElement(IsNullable = true)] public string Two { get; set; }
你可以把它表示为
我相信这篇文章中的人有同样的问题吗? 也许它可以为您提供解决方案?
C#xml序列化