我有以下代码将对象输出到 XML 文件:
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>
有任何想法吗?:)