【问题标题】:The XML element named 'name' from namespace references distinct types命名空间中名为“name”的 XML 元素引用了不同的类型
【发布时间】:2012-05-10 10:37:58
【问题描述】:

请帮忙。从服务器反序列化数据时出错,

命名空间“”中的顶部 XML 元素“名称”引用了不同的类型 Object1.LocalStrings 和 System.String。使用 XML 属性指定 元素或类型的另一个 XML 名称或命名空间。

我有一个 ObjectType 类,其中包含属性 Name 和 List<SupportedIp>。 SupportedIp 类也包含属性名称。请参考我下面的代码:

[XmlRootAttribute("SupportedIp", Namespace = "http://test.com/2010/test", IsNullable = false)]
public partial class SupportedIp
{[XmlElementAttribute(Namespace = "")]
    public string Name
    {
        get;
        set;
    } .... }


[GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[SerializableAttribute()]
[DebuggerStepThroughAttribute()]
[DesignerCategoryAttribute("code")]
[XmlTypeAttribute(Namespace = "http://test.com/2010/test")]
[XmlRootAttribute("ObjectType", Namespace = "http://test.com/2010/test", IsNullable = false)]
public partial class ObjectType
{

    /// <remarks/>
    [XmlElementAttribute(ElementName = "", Namespace = "")]
    public LocalStrings Name
    {
        get;
        set;
    }

    /// <remarks/>
    [XmlArrayAttribute(ElementName = "Supportedip", Namespace = "")]
    [XmlArrayItemAttribute(IsNullable = false, Namespace = "")]
    public List<Supportedip> Supportedip
    {
        get;
        set;
    }
}

当应用程序到达 XmlSerializer 部分时,会显示错误。我看过一些相关的帖子,但没有具体的答案。

【问题讨论】:

    标签: xml c#-4.0 namespaces xml-serialization


    【解决方案1】:

    从你写的我认为问题在于你有相同的元素名称(namespace="", name="Name") 具有两种不同类型的内容(字符串类型和本地字符串类型),这在 xml 中是非法的。这意味着每个 xml 解析器都应该引发您打印的致命错误。解决方案是更改元素的名称或使用相同的名称但将它们与不同的名称空间相关联。例如,而不是:

    [XmlElementAttribute(Namespace = "")]
    

    你可以说:

    [XmlElementAttribute(Namespace = "http://test.com/2010/test")]
    

    核心问题似乎是 XMLSerializer 使用 XSD 模式验证。这意味着您定义的每个 XmlElementAttribute 都附加了一个类型(更多信息来自 here)。 XSD 约束之一是“Element Declarations Consistent”约束,这意味着任何两个具有相同名称(和命名空间)的元素都必须具有相同的类型(更多信息来自 here)。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      您在方法标头中声明的参数对于命名空间中的所有 Web 方法必须是唯一的。因为参数是soap:body 的顶级xml 标签。祝你好运。

      【讨论】:

        【解决方案3】:

        读取错误: 使用 XML 属性为元素指定另一个 XML 名称或命名空间

        例子:

        [XmlElement("Animal", typeof(Dog), Namespace = "...Dog")]
        [XmlElement("Animal", typeof(Cat), Namespace = "...Cat")]
        public Animal Animal;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-11
          • 1970-01-01
          • 2022-06-10
          • 2016-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多