【问题标题】:How do I troubleshoot this exception when creating an XmlSerializer object?创建 XmlSerializer 对象时如何解决此异常?
【发布时间】:2011-05-01 10:54:59
【问题描述】:

我在 http://www.w3.org/2001/XMLSchema.xsd 下载了 XML Schemas for XML Schemas。

然后我使用 XSD.EXE 从下载的文件创建一个类。我给班级打电话schema.cs

然后我执行了这行代码:

XmlSerializer serializer = new XmlSerializer(typeof(schema));

得到了这个错误:

XML 元素“注释”来自 命名空间 'http://www.w3.org/2001/XMLSchema' 是 已经存在于当前范围内。

如何在不破坏架构的情况下找到重复元素并修复它?

【问题讨论】:

  • 可能是异常有行号和位置号。你能添加这些吗?
  • @Pieter:异常不包含行号,内部异常也不包含。
  • 而且您根本不知道注释会抛出什么?我查看了 XSD,看起来有很多范围有多个注释。
  • @Pieter:不,我没有。这是基本问题,是可见性。
  • @0xA3:我正在尝试阅读 another XML schema 并对其进行分析。

标签: c# xml xml-serialization xsd xsd.exe


【解决方案1】:

我认为生成的类有缺陷。

我更改了属性以修复第一个错误,但发现了一个新错误。

/// <remarks/>
//[System.Xml.Serialization.XmlElementAttribute("annotation", typeof(annotation))]
[System.Xml.Serialization.XmlElementAttribute("Items", typeof(annotation))]
[System.Xml.Serialization.XmlElementAttribute("import", typeof(import))]
[System.Xml.Serialization.XmlElementAttribute("include", typeof(include))]
[System.Xml.Serialization.XmlElementAttribute("redefine", typeof(redefine))]
public openAttrs[] Items {
    get {
        return this.itemsField;
    }
    set {
        this.itemsField = value;
    }
}

【讨论】:

  • 我确实使用了早期版本的 XSD,所以我使用您引用的版本再次运行它,并进行了文件比较。这两个文件之间的唯一区别是 CompilerGenerated 属性版本,所以我没有费心去测试新文件。诡异的。我会测试新文件并通知您。
  • 我认为问题仍然存在(Break on all errors 已关闭)。我认为生成的类虽然很糟糕......
  • 是的,它抛出了同样的异常。
【解决方案2】:

因为注释元素只是 cmets,您可以尝试简单地过滤掉所有这些元素。只需首先将 XML 加载到 XDocument 并删除所有注释元素。

【讨论】:

  • 很遗憾,我需要 cmets。
  • 看到我的评论了吗?你有异常的行号/位置号吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多