【问题标题】:XML error during deserialize反序列化期间的 XML 错误
【发布时间】:2017-05-30 11:52:00
【问题描述】:

我在尝试将 XML 反序列化为对象时遇到问题。我的 XML 看起来像:

<?xml version="1.0" encoding="utf-16"?>
<Products
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <AllProducts>
        <Product>
            <ID>8</ID>
            <GID>51280</GID>
            <Kod>RNIKAKC1.6</Kod>
            <Name>SB-800</Name>
            <Ean>0018208048014</Ean>
            <CommodityGroup>
                <ID>86</ID>
                <Name>AKCESORIA FOTO</Name>
                <Path>
                    <Category>
                        <ID>60798</ID>
                        <Name>ARCHIWALNE</Name>
                    </Category>
                </Path>
            </CommodityGroup>
         </Product>
....
Next products
...

我的方法代码:

var MemoryStream = APIAccess.DownloadFileToStream("example.xml", "exampleContainer");
            using (MemoryStream)
            {
                MemoryStream.Position = 0;
                using (StreamReader StreamReader = new StreamReader(MemoryStream))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(CommodityGroup));
                    var products = serializer.Deserialize(StreamReader);
                }
            }

方法 DownloadFileToStream 运行良好,因为它在其他类中很有用。

我收到错误:

InvalidOperationException: Products xmlns='' 不是预期的。

我想创建一个 Node CommodityGroup 的对象。我创建了选择此节点的类,将其复制并粘贴到新类中,例如 Paste Special -> XML

这个类的属性如下:

[Serializable()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlTypeAttribute(AnonymousType = true)]
[XmlRootAttribute(Namespace = "CommodityGroup", IsNullable = false)]

我不知道如何修复它。当我添加到 XML Serializer 参数 new XmlRootAttribute("Products") 中时,我得到了“0”值。

你有什么建议吗?

【问题讨论】:

  • 删除命名空间,它应该可以工作。查看stackoverflow.com/questions/2615892/…了解更多信息。
  • 我无法更改 xml 文件
  • 您是否手动将Namespace = "CommodityGroup" 添加到生成的类中?为什么?提交的 xml 不包含此命名空间。
  • 是的,自动生成了`Namespace = ""`。只是想尽一切办法解决这个问题

标签: c# .net xml serialization


【解决方案1】:

如果你只想反序列化 xml 文档的一部分,你应该跳过不必要的节点。

使用XmlReader

using (StreamReader StreamReader = new StreamReader(MemoryStream))
using (var xmlReader = XmlReader.Create(StreamReader))
{
    xmlReader.ReadToFollowing("CommodityGroup");
    XmlSerializer serializer = new XmlSerializer(typeof(CommodityGroup));
    var commodityGroup = (CommodityGroup)serializer.Deserialize(xmlReader);
}

【讨论】:

  • 用那个方法我有同样的例外,但是产品 xmls,我有 CommodityGroup xmls。我已经添加到序列化程序参数new XmlRootAttribute("CommodityGroup") 现在我有异常OverflowException: Value was either too large or too small for an unsigned byte.
  • 我已将 CommodityGroup 类中的值类型从 ushort 更改为 Int,这似乎可行。我需要更多地调试它,我会给出回应;)
猜你喜欢
  • 2014-03-31
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
相关资源
最近更新 更多