2009-07-11 80 views
3

我有以下代碼:與XML序列化(.NET)自定義節點名稱

public class Foo {} 

static class Program { 
    [XmlElement("foo")] // Ignored :(
    static public List<Foo> MyFoos { get; private set; } 

    public static void Main() { 
     MyFoos.Add(new Foo()); 
     MyFoos.Add(new Foo()); 

     XmlSerializer configSerializer = 
      new XmlSerializer(typeof(List<Foo>), new XmlRootAttribute("foos")); 
     using (TextWriter w = new StreamWriter("test.xml")) 
     { 
      s.Serialize(w, MyFoos); 
     } 
    } 
} 

將會產生下面的XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<foos xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Foo /> 
    <Foo /> 
</foos> 

我真的想擁有的是Foo元素標記爲foo,相反......我意識到這主要是表面化妝,但它符合XML中通常被認爲正常的東西。

回答

10

如果直接設置元素的名稱應該工作...

[XmlElement(ElementName = "foo")] 

見例如here。它必須是靜態的嗎?如果是這樣,這是沒有幫助的,但是這個工作正常(每加評論往返)...

namespace TestSerial 
{ 
    public class Foo 
    { 
     public int Value 
     { 
      get; 
      set; 
     } 
    } 
    public class SerializeMe 
    { 
     private List<Foo> _foos = new List<Foo>(); 
     public SerializeMe() 
     { 
     } 

     [XmlElement("foo")] 
     public List<Foo> MyFoos { get { return _foos; } } 

    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var fs = new SerializeMe(); 
      fs.MyFoos.Add(new Foo() { Value = 1 }); 
      fs.MyFoos.Add(new Foo() { Value = 2 }); 

      var s = new XmlSerializer(typeof(SerializeMe), new XmlRootAttribute("foos")); 
      using (var w = new StreamWriter(@"c:\temp\test.xml")) 
      { 
       s.Serialize(w, fs); 
      } 

      using (var r = new StreamReader(@"c:\temp\test.xml")) 
      { 
       var o = s.Deserialize(r); 
       var fs2 = (SerializeMe)o; 

       fs2.MyFoos.Select(f => f.Value).ToList().ForEach(Console.WriteLine); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 

編輯:(馬太福音,OP)

我的最終解決方案,我認爲對上述的改進是:

public class Foo {} 

[XmlRoot("foos")] 
public class FooList 
{ 
    public FooList() { Foos = new List<Foo>(); } 
    [XmlElement("foo")] 
    public List<Foo> Foos { get; set; } 
} 

static class Program 
{ 
    static private FooList _foos = new FooList(); 
    static public List<Foo> MyFoos { get { return _foos; } } 

    public static void Main() 
    { 
     MyFoos.Add(new Foo()); 
     MyFoos.Add(new Foo()); 

     XmlSerializer configSerializer = 
      new XmlSerializer(typeof(FooList)); 

     using (TextReader r = new StreamReader("test.xml")) 
     { 
      _foos = (FooList)configSerializer.Deserialize(r); 
     } 

     using (TextWriter w = new StreamWriter("test.xml")) 
     { 
      configSerializer.Serialize(w, _foos); 
     } 
    } 
} 
+1

XmlElementAttribute在類定義上是不允許的:屬性'XmlElement'在這個聲明類型上是無效的。它只對'property,indexer,field,param,return'聲明有效。 – 2009-07-11 02:45:02