2012-07-06 174 views
2

我序列化对象到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.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>

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

回答

2

使用

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

可以代表它作为<Two xsi:nil="true" />

+0

这似乎并没有在所有更改XML,我已经发布我上面使用完全相同的代码,我刚刚在我的第二个自动属性上添加了[[XmlElement(IsNullable = true)]',我仍然得到相同的输出。 – JMK 2012-07-06 13:01:01

+0

对不起,如果我误解了这个问题。如果你使用上面的代码,在xml中什么都不会改变。如果'Two = null',你会得到'xsi:nil'。 – Shymep 2012-07-06 13:06:38

+0

当然啊,哈哈!我不确定我们发送文件的人是否会对此感到满意,但我会给它一个机会。谢谢 – JMK 2012-07-06 13:11:53

0

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

C# xml serialization