我使用以下代码将对象序列化为 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<MyClass>(thisClass, @"C:\Users\JMK\Desktop\x.xml");
}
static void Serialize<T>(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:
<?xml version="1.0" encoding="utf-8"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<One>Foo</One>
<Two />
<Three>Bar</Three>
</MyClass>
这一切都很好,除了一件事。如果我的值之一为空,我不能从 XML 中省略它,它必须存在,我不能将它表示为<Two />
,而是我需要将它表示为<Two></Two>
。
这可以使用我目前的方法吗?