C# 使用 Object & 添加 XML 属性XML序列化程序 [英] C# Add an XML Attribute Using Object & XMLSerializer
本文介绍了C# 使用 Object & 添加 XML 属性XML序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码将对象输出到 XML 文件:
I have the following code which outputs an object to an XML file:
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>
但是,我希望输出在每个 Definition 标记项上包含一个属性,如下所示:
However, I would like the output to include an attribute on each of the Definition tag items like this:
<?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>
有什么想法吗?:)
推荐答案
您将不得不使用自定义类型而不是字符串.
You will have to use a custom type instead of a string.
public class Definition
{
[XmlAttribute("active")]
public bool Active;
[XmlText]
public string Text;
}
然后像这样定义Definitions
属性
[XmleElement("string")]
public Definition[] Definitions { get; set; }
这篇关于C# 使用 Object & 添加 XML 属性XML序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文