我的节目:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace Test
{
public enum TestEnum
{
[XmlEnum(null)]
Nothing,
[XmlEnum("A")]
A,
[XmlEnum("B")]
B
}
public class TestClass
{
[XmlAttribute("firstName")]
public string Name { get; set; }
[XmlAttribute("testEnum")]
public TestEnum TestEnum { get; set; }
}
class Program
{
static void Main(string[] args)
{
TestClass testClass1 = new TestClass() { Name = "TestClass1", TestEnum = TestEnum.A };
XmlSerializer serializer1 = new XmlSerializer(typeof(TestClass));
StringWriter stringWriter1 = new StringWriter();
serializer1.Serialize(stringWriter1, testClass1);
Console.WriteLine(stringWriter1.ToString());
Console.WriteLine();
TestClass testClass2 = new TestClass() { Name = "TestClass2", TestEnum = TestEnum.Nothing };
XmlSerializer serializer2 = new XmlSerializer(typeof(TestClass));
StringWriter stringWriter2 = new StringWriter();
serializer2.Serialize(stringWriter2, testClass2);
Console.WriteLine(stringWriter2.ToString());
}
}
}
提供以下输出:
<?xml version="1.0" encoding="utf-16"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
firstName="TestClass1" testEnum="A" />
<?xml version="1.0" encoding="utf-16"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
firstName="TestClass2" testEnum="Nothing" />
但是在Enum Value“Nothing”的情况下,我想要以下输出(一直删除属性和值):
<?xml version="1.0" encoding="utf-16"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
firstName="TestClass2" />
我该怎么做? [XmlIgnore]对特定的枚举值不起作用。