【问题标题】:Deserialize XML arrays using C#使用 C# 反序列化 XML 数组
【发布时间】:2020-01-31 14:58:19
【问题描述】:

如果我有如下 XML:

<?xml version="1.0" encoding="UTF-8" ?>
<Config>
    <Interface>
        <Theme>Dark</Theme>
        <Mode>Advanced</Mode>
    </Interface>
    <Export>
        <Destination>\\server1.example.com</Destination>
        <Destination>\\server2.example.com</Destination>
        <Destination>\\server3.example.com</Destination>
    </Export>       
</Config>

我可以通过以下方法轻松反序列化XML并获取“接口”部分中的元素值:

using System;
using System.IO;
using System.Xml.Serialization;

static void Main(string[] args)
    {
        var serializer = new XmlSerializer(typeof(Config));

        using (var stream = new FileStream(@"C:\Temp\Config.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var config = (Config)serializer.Deserialize(stream);

            Console.WriteLine($"Theme: {config.Interface.Theme}");
            Console.WriteLine($"Mode: {config.Interface.Mode}");
            Console.ReadKey();
        }
    }


[Serializable, XmlRoot("Config")]
public class Config
{
    public Interface Interface { get; set; }
}

public struct Interface
{
    public string Theme { get; set; }
    public string Mode { get; set; }
}

我应该如何反序列化“导出”部分中的“目标”元素数组,以便循环遍历数组对象以打印值?

foreach (destination d in export)
{
Console.WriteLine(destination);
}

【问题讨论】:

  • 你可以这样使用:cs public class Export { public List&lt;string&gt; Destination { get; set; } } public class Config { public Interface Interface { get; set; } public Export Export { get; set; } }
  • 我确实尝试过,但是当我尝试执行Console.WriteLine(config.Export.Destination[0]);时,它只会导致“索引超出范围”@

标签: c# arrays xml serialization


【解决方案1】:

您需要将带有Destination 标识符的XmlElement标签添加到您的列表声明中以填充它

[Serializable, XmlRoot("Config")]
public class Config
{
    public Interface Interface { get; set; }

    public Export Export { get; set; }
}

public struct Export
{
    [XmlElement("Destination")]
    public List<string> Destinations { get; set; }
}

然后您可以通过以下方式访问这些值

foreach (string destination in config.Export.Destinations)
{
    Console.WriteLine(destination);
}

您还可以通过添加XmlText 标签来创建自定义Destination 类,而不是使用字符串列表

public struct Export
{
    [XmlElement("Destination")]
    public List<Destination> Destinations { get; set; }
}

public struct Destination
{
    [XmlText()]
    public string Value { get; set; }
}

foreach (Destination destination in config.Export.Destinations)
{
    Console.WriteLine(destination.Value);
}

【讨论】:

  • @Quantum_Kernel 我做了一个小改动,你可能会感兴趣
猜你喜欢
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
相关资源
最近更新 更多