gpt4 book ai didi

C# 使用对象和 XMLSerializer 添加 XML 属性

转载 作者:行者123 更新时间:2023-11-30 22:27:38 25 4
gpt4 key购买 nike

我有以下代码将对象输出到 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>

有什么想法吗? :)

最佳答案

您将不得不使用自定义类型而不是字符串。

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

[XmlText]
public string Text;
}

然后像这样定义Definitions属性

[XmlElement("string")]
public Definition[] Definitions { get; set; }

关于C# 使用对象和 XMLSerializer 添加 XML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11182162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com