c# - 反序列化每个字符串元素的 XML 元素列表

标签 c# xml serialization

我无法使用 C# 反序列化 XML 的以下部分

<mainfile>
    <portfolio>
        <fotos>
            <foto> <!CDATA[https://whatever.com/fotos/E/400/photo.JPG]]>
            </foto>
        </fotos>
    </portfolio>
    <portfolio>
        <fotos>
            <foto> <!CDATA[https://whatever.com/fotos/E/400/photo1.JPG]]>
            </foto>
        </fotos>
    </portfolio>
</mainfile>

我认为它应该很简单,但是在反序列化时它总是返回一个空列表。这是代码:

[XmlRoot("mainfile")]
public class MainFile
{
    public MainFile()
    {
        porftolios= new List<Portfolio>();
    }

    [XmlElement("portfolio")]
    public List<Portfolio> Portfolios{ get; set; }
}

public class Portfolio
{
    ....
    [XmlElement("fotos")]
    public List<Foto> Fotos { get; set; }
}

public class Foto
{
    [XmlText]
    public string data{ get; set; }
}

谢谢。

编辑。 从 HimBromBeere 的解决方案中,我修改了以下代码,结果成功:

public class Portfolio
{
    ....
    [XmlArray("fotos")]
    [XmlArrayItem("foto")]
    public List<Foto> Fotos { get; set; }
}

public class Foto
{
    [XmlText]
    public string data{ get; set; }
}

最佳答案

当对列表类型使用 XmlElement 时,生成的 xml 中的容器列表元素将丢失。由于您确实为您的fotos标签设置了容器,因此您应该为它使用XmlArrayItem:

public class Portfolio
{
    [XmlArray("fotos")]
    [XmlArrayItem("foto")]
    public List<Foto> Fotos { get; set; }
}

如果您可以更改 xml,但我建议为您的收藏使用一致的样式,也可以为您的 portfolio 使用容器,或者为您的 fotos 省略它>.

关于c# - 反序列化每个字符串元素的 XML 元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54861965/

相关文章:

c# - 如何将图像裁剪成圆形?

c# - C#中的继承,where T : new() mean? 是做什么的

c# - 如何为数据网格的 NewItemPlaceholder 行添加模板?

c# - 在 XSLT 中使用从 C# 代码传递的参数

c# - 在给定的字符串中打印不可打印的字符?

java - 有没有办法将字符串数组作为变量传递给服务器端 Xquery 脚本?

xml - 如何使用 XSL 转义 XML 内容以将其安全地输出为 JSON?

c# - 是否可以通过 COM 公开 DateTime 字段?

c# - 为什么需要 DataContractSerializer 按字母顺序排序的 XML?

c# - 按字母顺序序列化 JSON