2017-01-20 16 views
2

類型:我將如何詮釋這個.NET類型以連載從以下XML/deserialise到/,使用的System.Xml.Serialization

public class Foo 
{ 
    public string Bar { get; set; } 
    public string Fred { get; set; } 
} 

實例

Foo x = new Foo { Bar = "Hi", Fred = "hey yourself" }; 

的XML:

<Foo> 
    <Bar>Hi</Bar> 
    <John>       <!-- Note extra layer --> 
     <Fred>hey there</Fred> 
    </John> 
</Foo> 

注意額外John標籤,但沒有對John創建一個特殊類型。如果我不能註釋它,我該如何以編程方式控制序列化過程。

+0

哪裏約翰標籤從何而來?你的意思是你想嵌套一個標籤與其他自定義標籤? –

+0

這就是我想要額外標籤的問題。 –

+0

我認爲你應該使用XmlDocument並編寫自己的代碼,而不是使用XmlSerializer。也許你最後的選擇 –

回答

0

試試這個:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 
using System.Runtime; 
using System.Runtime.InteropServices; 

namespace ConsoleApplication42 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 

      Foo x = new Foo { Bar = "Hi", Fred = "hey yourself" }; 
      //<Foo> 
      // <Bar>Hi</Bar> 
      // <John>       <!-- Note extra layer --> 
      //  <Fred>hey there</Fred> 
      // </John> 
      //</Foo> 

      XElement foo = new XElement("Foo", new object[] { 
       new XElement("Bar", x.Bar), 
       new XElement("John", new XElement("Fred", x.Fred)) 
      }); 

     } 
    } 
    public class Foo 
    { 
     public string Bar { get; set; } 
     public string Fred { get; set; } 
    } 

} 
+0

謝謝,但我已經在使用System.Xml.Serialization,我的問題只是一個更大的一組我正在序列化的類型的例子。我可以將其掛鉤到System.Xml.Serialization過程中嗎? –

+0

你將不得不編寫一個自定義序列化程序。我從來沒有寫過一個。標準序列化程序通過類枚舉並添加「約翰」,在你不在的地方添加「約翰」。我不知道如何使用serilizer可以做到這一點。 – jdweng

相關問題