2

我使用以下代码将对象序列化为 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>

这可以使用我目前的方法吗?

4

2 回答 2

2

使用

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

您可以将其表示为<Two xsi:nil="true" />

于 2012-07-06T12:55:39.287 回答
0

我相信这篇文章中的人也有同样的问题?也许它可以为您提供解决方案?

C# xml 序列化

于 2012-07-06T12:40:47.187 回答