从使用 XSD.exe 生成的 XML 中反序列化类

发布于 2024-08-31 14:16:02 字数 3278 浏览 1 评论 0原文

我有从 .xsd 生成的类(使用 xsd.exe),我可以很好地序列化它,但是当我尝试反序列化它时,我收到错误:

{"<XMLLanguages xmlns='http://tempuri.org/XMLLanguages.xsd'> was not expected."}

我搜索了几个小时,发现大多数人的问题在于不在其 xsd/xml 中声明名称空间,不在其类中定义名称空间等,但我找不到解决问题的方法。

以下是相关类的代码片段。

    <?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLLanguages"
    targetNamespace="http://tempuri.org/XMLLanguages.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLLanguages.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="XMLLanguages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Tier" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="L" minOccurs="1" maxOccurs="unbounded" type="Language"/>
            </xs:sequence>
            <xs:attribute name="TierID" type="xs:int"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="Language">
    <xs:sequence>
      <xs:element name="LangID" type="xs:int"/>
      <xs:element name="Tier" type="xs:int"/>
      <xs:element name ="Name" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name ="PassRate" type="xs:int"/>
  </xs:complexType>
</xs:schema>

类:

    /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://tempuri.org/XMLLanguages.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLLanguages.xsd", IsNullable = false)]
public partial class XMLLanguages
{
    private List<XMLLanguagesTier> tierField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Tier")]
    public List<XMLLanguagesTier> Tiers {
        get {
            return this.tierField;
        }
        set {
            this.tierField = value;
        }
    }
}

以及 XML 中导致错误的行:

<XMLLanguages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/XMLLanguages.xsd">

反序列化方法:

public static object Deserialize(XmlDocument xml, Type type)
    {
        XmlSerializer s = new XmlSerializer(type);
        string xmlString = xml.OuterXml.ToString();
        byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
        MemoryStream ms = new MemoryStream(buffer);
        XmlReader reader = new XmlTextReader(ms);
        Exception caught = null;

        try
        {
            object o = s.Deserialize(reader);
            return o;
        }

        catch (Exception e)
        {
            caught = e;
        }
        finally
        {
            reader.Close();

            if (caught != null)
                throw caught;
        }
        return null;
    }

I have classes generated (using xsd.exe) from an .xsd that I can serialize just fine, but when I try and deserialize it, I get the error:

{"<XMLLanguages xmlns='http://tempuri.org/XMLLanguages.xsd'> was not expected."}

I've searched for a couple of hours and found most peoples problems lie in not declaring namespaces in their xsd/xml, not defining namespaces in their classes, etc, but I can't find a solution for my problem.

Here are code snippets for the relevant classes.

    <?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLLanguages"
    targetNamespace="http://tempuri.org/XMLLanguages.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLLanguages.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="XMLLanguages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Tier" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="L" minOccurs="1" maxOccurs="unbounded" type="Language"/>
            </xs:sequence>
            <xs:attribute name="TierID" type="xs:int"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="Language">
    <xs:sequence>
      <xs:element name="LangID" type="xs:int"/>
      <xs:element name="Tier" type="xs:int"/>
      <xs:element name ="Name" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name ="PassRate" type="xs:int"/>
  </xs:complexType>
</xs:schema>

And the class:

    /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://tempuri.org/XMLLanguages.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://tempuri.org/XMLLanguages.xsd", IsNullable = false)]
public partial class XMLLanguages
{
    private List<XMLLanguagesTier> tierField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Tier")]
    public List<XMLLanguagesTier> Tiers {
        get {
            return this.tierField;
        }
        set {
            this.tierField = value;
        }
    }
}

And a the line in XML causing the error:

<XMLLanguages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/XMLLanguages.xsd">

Deserializing method:

public static object Deserialize(XmlDocument xml, Type type)
    {
        XmlSerializer s = new XmlSerializer(type);
        string xmlString = xml.OuterXml.ToString();
        byte[] buffer = ASCIIEncoding.UTF8.GetBytes(xmlString);
        MemoryStream ms = new MemoryStream(buffer);
        XmlReader reader = new XmlTextReader(ms);
        Exception caught = null;

        try
        {
            object o = s.Deserialize(reader);
            return o;
        }

        catch (Exception e)
        {
            caught = e;
        }
        finally
        {
            reader.Close();

            if (caught != null)
                throw caught;
        }
        return null;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人疚 2024-09-07 14:16:03

我使用下面的代码并且工作正常。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Report"
           targetNamespace="http://www.xyz.com/Report.xsd"
           elementFormDefault="qualified"
           xmlns="http://www.xyz.com/Report.xsd"
           xmlns:mstns="http://www.xyz.com/Report.xsd"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="Report">
  <xs:complexType>
  ...

我将 xsd.exe 与 /n:xyz 命名空间选项一起使用。

这似乎工作正常,所以我认为您的问题一定是 tempuri.org 域名。

希望这对您有所帮助。

理查德.

I use the following code and it works fine.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Report"
           targetNamespace="http://www.xyz.com/Report.xsd"
           elementFormDefault="qualified"
           xmlns="http://www.xyz.com/Report.xsd"
           xmlns:mstns="http://www.xyz.com/Report.xsd"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="Report">
  <xs:complexType>
  ...

I use xsd.exe with the /n:xyz namespace option.

This seems to work fine, so I assume your problem must be with the tempuri.org domain name.

Hope this is of some help.

Richard.

高速公鹿 2024-09-07 14:16:03

您需要从根中删除 targetNamespace 属性,并在 XMLLanguages 节点之前添加以下节点:

<xs:import namespace="http://www.w3.org/2001/XMLSchema"/>

上面将允许您反序列化,但我感觉到即将出现其他问题。您面临的问题是,当您定义多个复杂类型时,您不能使用 targetNamespace 属性 - 欢迎来到模式命名空间地狱......

You need to remove the targetNamespace attribute from the root, and add the following node before the XMLLanguages node:

<xs:import namespace="http://www.w3.org/2001/XMLSchema"/>

The above will let you deserialize, but I sense other problems on the horizon. The problem you were facing was that when you define multiple complex types, you can't use the targetNamespace attribute -- welcome to schema namespace hell...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文