C# 将对象序列化为XML时以不同方式表示空值

C# 将对象序列化为XML时以不同方式表示空值,c#,xml,C#,Xml,我使用以下代码将对象序列化为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.E

我使用以下代码将对象序列化为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; }
    }
}
使用System.IO;
使用System.Xml.Serialization;
命名空间控制台应用程序2
{
班级计划
{
静态void Main(字符串[]参数)
{
MyClass thisClass=newMyClass(){One=“Foo”,Two=string.Empty,Three=“Bar”};
序列化(thisClass,@“C:\Users\JMK\Desktop\x.xml”);
}
静态void序列化(tx,字符串文件名)
{
XmlSerializer v=新的XmlSerializer(typeof(T));
TextWriter f=新的StreamWriter(文件名);
v、 序列化(f,x);
f、 Close();
}
}
公共类MyClass
{
公共字符串One{get;set;}
公共字符串二{get;set;}
公共字符串三{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>

福
酒吧
这一切都很好,除了一件事。如果我的一个值为null,我不能从XML中忽略它,它需要存在,我不能将它表示为
,而是需要将它表示为


用我目前的方法可以吗?

我相信本文中的人也有同样的问题? 也许它能为你提供一个解决方案

使用

[XmlElement(IsNullable = true)]
public string Two { get; set; }

您可以将其表示为

这似乎根本不会改变XML,我已经发布了我在上面使用的确切代码,我刚刚在我的第二个自动属性上添加了
[xmlement(IsNullable=true)]
,我仍然得到了相同的输出。如果我误解了这个问题,很抱歉。如果使用上面的代码,xml中的任何内容都不会改变。如果
Two=null
,您将得到
xsi:nil
。啊,当然,doh!我不确定我们发送文件的人是否会对此感到满意,但我会尝试一下。谢谢