【问题标题】:C# xml deserializingC# xml 反序列化
【发布时间】:2012-09-08 14:57:11
【问题描述】:

我有这门课叫identity

namespace Game.World.Entities
{
    [XmlRoot("Identity")]
    public class Identity
    {
        public string Name { get; set; }
        public string Texture { get; set; }
        public string HeroType { get; set; }

        public Stats Stats { get; set; }
        public ActiveAbilitites ActiveAbilitites { get; set; }
        public PassiveAbilitites PassiveAbilitites { get; set; }
    }

    public class ActiveAbilitites
    {
        [XmlElement("AbilityId")]
        public List<int> ActiveAbilitiesId { get; set; }
    }

    public class PassiveAbilitites
    {
        [XmlElement("AbilityId")]
        public List<int> PassiveAbilitiesId { get; set; }
    }

    public class Stats
    {
        public int Health { get; set; }
        public int MagicDamage { get; set; }
        public int PhysicalDamage { get; set; }
        public int Defense { get; set; }
    }
}

我已经将该类序列化为一个 xml 文档:

<?xml version="1.0" encoding="utf-8"?>
<Identity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>foo</Name>
  <Texture>player</Texture>
  <HeroType>tracker</HeroType>
  <Stats>
    <Health>5</Health>
    <MagicDamage>5</MagicDamage>
    <PhysicalDamage>5</PhysicalDamage>
    <Defense>5</Defense>
  </Stats>
  <ActiveAbilitites>
    <AbilityId>1</AbilityId>
    <AbilityId>2</AbilityId>
    <AbilityId>3</AbilityId>
  </ActiveAbilitites>
  <PassiveAbilitites>
    <AbilityId>1</AbilityId>
    <AbilityId>2</AbilityId>
    <AbilityId>3</AbilityId>
  </PassiveAbilitites>
</Identity>

但是,当我尝试将 xml 反序列化为 identity 对象时,出现错误

xml文档有错误(2,2).....
System.InvalidOperationException 不是预期的。
在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read6_ArrayOfIdentity()

现在这让我很困惑,因为 xml 来自序列化,所以我不知道为什么我不能反序列化它。我假设我在某处错过了注释标签,任何关于此事的帮助都会很棒。

【问题讨论】:

  • 你能告诉我们你用于机器人序列化和反序列化的代码吗?
  • 原来是反序列化代码,如果我从 .xml 文件中读取它,它工作正常,但是当我从字符串反序列化 xml 时发生错误。当我得到它与字符串编辑一起使用时,我会更新此评论不知道我做了什么来搞乱解串器,但我现在让它使用字符串。 var reader = new StringReader(template); var identity = (Identity) serializer.Deserialize(reader);
  • 请不要将答案放在问题中。我删除了它。

标签: c# xml deserialization


【解决方案1】:

这原来是我如何反序列化代码的问题。我不知道我做了什么把它搞砸了,但我假设这与我的字符串阅读器有关。我刚刚从Deserialize from string instead TextReader 复制并粘贴了一些示例代码,现在可以正常工作了。

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多