2012-06-25 40 views
2

我有下面的代碼的對象輸出到一個XML文件中:C#添加XML屬性使用對象和XMLSerializer的

using System; 
using System.IO; 
using System.Collections.Generic; 
using System.Reflection; 
using System.Xml; 
using System.Xml.Serialization; 

namespace TrailBlazerReloaded 
{ 
    public class Config 
    { 
     Config config = null; 
     XmlSerializer serializer = new XmlSerializer(typeof(Config)); 

     public Config() 
     { 
      CollectionPaths = null; 
      Definitions = null; 
      TrailerPath = null; 
     } 

     public string Version { get; set; } 

     public string[] CollectionPaths { get; set; } 

     public string[] Definitions { get; set; } 

     public string[] TrailerPath { get; set; } 

     public void WriteConfig(Config configToSave) 
     { 
      serializer = new XmlSerializer(typeof(Config)); 
      TextWriter textWriter = new StreamWriter(@"config.xml"); 
      serializer.Serialize(textWriter, configToSave); 
      textWriter.Close(); 
     } 

     public Config ReadConfig() 
     { 
      if (File.Exists(@"Config.xml")) 
      { 
       var reader = new StreamReader("Config.xml"); 
       config = (Config) serializer.Deserialize(reader); 
       reader.Close(); 
      } 

      return config; 
     } 

     public static string GetConfigFilePath() 
     { 
      return Assembly.GetExecutingAssembly().Location + ".config"; 
     } 

    } 
} 

它返回以下結果:

<?xml version="1.0" encoding="utf-8"?> 
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Version>0.0.1</Version> 
    <CollectionPaths> 
    <string>F:\Trailblazer Test Folder 1</string> 
    <string>F:\Trailblazer Test Folder 2</string> 
    <string>F:\Trailblazer Test Folder 3 (100 Films)</string> 
    </CollectionPaths> 
    <Definitions> 
    <string>1080p</string> 
    <string>720p</string> 
    <string>480p</string> 
    </Definitions> 
    <TrailerPath> 
    <string>C:\</string> 
    </TrailerPath> 
</Config> 

不過,我想類似於輸出以在每個定義標記項目上包括像這樣的屬性:

<?xml version="1.0" encoding="utf-8"?> 
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Version>0.0.1</Version> 
    <CollectionPaths> 
    <string>F:\Trailblazer Test Folder 1</string> 
    <string>F:\Trailblazer Test Folder 2</string> 
    <string>F:\Trailblazer Test Folder 3 (100 Films)</string> 
    </CollectionPaths> 
    <Definitions> 
    <string active="true">1080p</string> 
    <string active="false">720p</string> 
    <string active="true">480p</string> 
    </Definitions> 
    <TrailerPath> 
    <string>C:\</string> 
    </TrailerPath> 
</Config> 

任何i DEAS? :)

回答

3

您將不得不使用自定義類型而不是字符串。

public class Definition 
{ 
    [XmlAttribute("active")] 
    public bool Active; 

    [XmlText] 
    public string Text; 
} 

然後定義像這樣

[XmleElement("string")] 
public Definition[] Definitions { get; set; } 
Definitions屬性