将 XML 反序列化为对象数组 [英] Deserialize XML to Object Array

查看:38
本文介绍了将 XML 反序列化为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 XML 文件反序列化为对象数组,但我收到的是空对象.我的问题看起来与此类似:如何将 xml 反序列化为数组对象? 但我似乎无法创建一个继承 IXmlSerializable 的类.也就是说,我认为这种方法没有必要.

I'm trying to deserialize an XML file to an object array, but I'm receiving empty objects. My question looks similar to this: How to Deserialize xml to an array of objects? but I can't seem to create a class which inherits IXmlSerializable. That said, I don't think that approach is necessary.

我做错了什么吗?

文件对象

 [XmlType("file")]
    public class File
    {
        [XmlElement("id")]
        public string Id { get; set; }

        [XmlElement("company_name")]
        public string Company_Name { get; set; }

        [XmlElement("docs")]
        public HashSet<doc> Docs { get; set; }
    }

文档对象

 [XmlType("doc")]
    public class Doc
    {
        [XmlElement("valA")]
        public string ValA { get; set; }

        [XmlElement("valB")]
        public string ValB { get; set; }
    }

XML

<?xml version="1.0" encoding="UTF-8"?>
  <files>
    <file>
      <id>12345</id>
      <company_name>Apple</company_name>
      <docs>
       <doc>
          <valA>Info</valA>
          <valB>More Info</valB>
       </doc>  
      </docs>
    </file>
    <file>
      <id>12345</id>
      <company_name>Microsoft</company_name>
      <docs>
       <doc>
          <valA>Even More Info</valA>
          <valB>Lots of it</valB>
       </doc>  
      </docs>
    </file>
  </files>

反序列化代码

XmlSerializer mySerializer = new XmlSerializer(typeof(File[]), new XmlRootAttribute("files"));
using (FileStream myFileStream = new FileStream("Files.xml", FileMode.Open))
{
    File[] r;
    r = (File[])mySerializer.Deserialize(myFileStream);
}

推荐答案

您已经使用 XMLAttribute 修饰了您的属性,但它们是您的 XML 中的元素.因此,将所有 XMLAttribute 更改为 XmlElement.

You have decorated your properties with XMLAttribute but they are elements in your XML. So, change all XMLAttribute to XmlElement.

[XmlType("file")]
public class File
{
    [XmlElement("id")]
    public string Id { get; set; }

    [XmlElement("company_name")]
    public string Company_Id { get; set; }

    [XmlArray("docs")]
    public HashSet<Doc> Docs { get; set; }
}

[XmlType("doc")]
public class Doc
{
    [XmlElement("valA")]
    public string ValA { get; set; }

    [XmlElement("valB")]
    public string ValB { get; set; }
}

此外,您的 XML 格式不正确.我想这是错字 -

Also you XML is not well formed. I guess this is typo though -

<company_name>Apple</company_id>
<company_name>Microsoft</company_id>

结束标签应该是 company_name -

<company_name>Apple</company_name>
<company_name>Microsoft</company_name>

这篇关于将 XML 反序列化为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆