XML命名空间中名为“name”的元素引用了不同类型。

13

请帮忙。我在从服务器反序列化数据时出现了错误,

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

我的类ObjectType包含属性Name和List<SupportedIp>。 SupportedIp类也包含属性Name。请参考下面的代码:

[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部分时,会显示错误。我看过一些相关的帖子,但没有明确的答案。

3个回答

19

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

[XmlElementAttribute(Namespace = "")]

你可以使用以下代码:

[XmlElementAttribute(Namespace = "http://test.com/2010/test")]
核心问题似乎在于XMLSerializer使用XSD模式验证。这意味着每个您定义的XmlElmentAttribute都附带了一个类型 (可以从此处了解更多信息)。 XSD约束之一是“元素声明一致”约束,这意味着具有相同名称(和命名空间)的任何两个元素必须具有相同的类型(可以从此处了解更多信息)。希望对你有所帮助。

0

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


0

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

示例:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接