简体   繁体   English

在 C# 反序列化期间,出现 System.InvalidOperationException: < xmlns=''> 不是预期的

[英]During C# deserialization, getting System.InvalidOperationException: < xmlns=''> was not expected

I'm new to XMLdeserialization.我是 XML 反序列化的新手。 I used xsd.exe to generate object classes for performing a deserialization on an existing XML file.我使用 xsd.exe 生成 object 类,用于对现有 XML 文件执行反序列化。 When I run my solution below, I get the error当我在下面运行我的解决方案时,我得到了错误

System.InvalidOperationException: < xmlns=''> was not expected System.InvalidOperationException: < xmlns=''> 不是预期的

on the s = (NewDataSet)xs.Deserialize(sr) call.s = (NewDataSet)xs.Deserialize(sr)调用上。 I looked this error up on Stack Overflow, and everyone says it's in the XMLRootAttribute line.我在 Stack Overflow 上查看了这个错误,每个人都说它在XMLRootAttribute行中。

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

How can I correct this line?我怎样才能纠正这条线? Or where can I find some documentation that explains how to correct it?或者我在哪里可以找到一些解释如何更正它的文档?

Also, why doesn't xsd.exe generate the correct XmlRootAttribute line in the first place?另外,为什么 xsd.exe 首先不生成正确的XmlRootAttribute行? Am I invoking this utility wrong?我调用这个实用程序错了吗? Or are there some situations the xsd.exe utility can't handle?或者是否存在 xsd.exe 实用程序无法处理的某些情况?

public class Program
{
    static void Main(string[] args)
    {
        SortedSet<string> symbolsEstablished = new SortedSet<string>();

        GetXmlDataSet("Expt 2buy.xml", ref symbolsEstablished);
    }

    public static void GetXmlDataSet(string fileName, ref SortedSet<string> symbols)
    {
        XmlSerializer xs = new XmlSerializer(typeof(NewDataSet));
        StreamReader sr = new StreamReader(@"C:\Users\mehl\AppData\Roaming\Fidelity Investments\WealthLabPro\1.0.0.0\Data\DataSets\" + fileName);
        NewDataSet s = (NewDataSet)xs.Deserialize(sr);
        Console.WriteLine(s.Items[0].DSString);
        sr.Close();
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class DataSet
    {
        private string nameField;
        private string scaleField;
        private string barIntervalField;
        private string dSStringField;
        private string providerNameField;

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string Name
        {
            get { return this.nameField; }
            set { this.nameField = value; }
        }

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string Scale
        {
            get { return this.scaleField; }
            set { this.scaleField = value; }
        }

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string BarInterval
        {
            get { return this.barIntervalField; }
            set { this.barIntervalField = value; }
        }

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string DSString
        {
            get { return this.dSStringField; }
            set { this.dSStringField = value; }
        }

        [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
        public string ProviderName
        {
            get { return this.providerNameField; }
            set { this.providerNameField = value; }
        }
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class NewDataSet
    {
        private DataSet[] itemsField;

        [System.Xml.Serialization.XmlElementAttribute("DataSet")]
        public DataSet[] Items
        {
            get { return this.itemsField; }
            set { this.itemsField = value; }
        }
    }
}

The entire above code segment is wrapped in a screener2wl namespace.上面的整个代码段都包装在 screener2wl 命名空间中。

And here's the XML file I'm trying to deserialize:这是我试图反序列化的 XML 文件:

<?xml version="1.0"?>
<DataSet xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Expt 2buy</Name>
  <Scale>Daily</Scale>
  <BarInterval>0</BarInterval>
  <DSString>AAL,AFSI,BEN,BIG,BLKB,CDK,COHR,CRUS,EGP,EPE,ETH,FB,HUM,LSTR,MDP,MSI,NYT,TAST,TER,TSO,TXN,UTHR,VASC,VLO,WRI,</DSString>
  <ProviderName>FidelityStaticProvider</ProviderName>
</DataSet>

Using xml linq:使用 xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            DataSet ds = doc.Descendants("DataSet").Select(x => new DataSet() {
                nameField = (string)x.Element("Name"),
                scaleField = (string)x.Element("Scale"),
                barIntervalField = (string)x.Element("BarInterval"),
                dSStringField = (string)x.Element("DSString"),
                providerNameField = (string)x.Element("ProviderName")
            }).FirstOrDefault();
        }
    }
    public partial class DataSet
    {
        public string nameField { get; set; }
        public string scaleField { get; set; }
        public string barIntervalField { get; set; }
        public string dSStringField { get; set; }
        public string providerNameField { get; set; }
    }
}

I got to thinking... isn't it odd xsd.exe would provide a code generated solution that defines two independent XmlRootAttribute nodes?我开始思考......这不是很奇怪 xsd.exe 会提供定义两个独立XmlRootAttribute 节点的代码生成解决方案吗? Can an XML file even have two Root Nodes? XML 文件甚至可以有两个根节点吗? Maybe the solutions xsd.exe generates shouldn't be taken too literally.也许 xsd.exe 生成的解决方案不应该过于字面意思。 :-) :-)

So after editing its solution, and removing one part with a second XmlRootAttribute defined, I got the solution below, which works.因此,在编辑其解决方案并删除定义了第二个 XmlRootAttribute 的一部分后,我得到了下面的解决方案,该解决方案有效。

namespace screener2wl
{
    public class Program
    {
        static void Main(string[] args)
        {
            SortedSet<string> symbolsEstablished = new SortedSet<string>();
            GetXmlDataSet("Expt 2buy.xml", ref symbolsEstablished);
        }

        public static void GetXmlDataSet(string fileName, ref SortedSet<string> symbols)
        {
            XmlSerializer xs = new XmlSerializer(typeof(DataSet));
            StreamReader sr = new StreamReader(@"C:\Users\mehl\AppData\Roaming\Fidelity Investments\WealthLabPro\1.0.0.0\Data\DataSets\" + fileName);
            DataSet s = (DataSet)xs.Deserialize(sr);
            Console.WriteLine(s.DSString);
            sr.Close();
        }

        [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
        [System.Xml.Serialization.XmlRootAttribute(IsNullable = false)]
        public class DataSet
        {
            private string nameField;
            private string scaleField;
            private string barIntervalField;
            private string dSStringField;
            private string providerNameField;

            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string Name
            {
                get { return this.nameField; }
                set { this.nameField = value; }
            }

            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string Scale
            {
                get { return this.scaleField; }
                set { this.scaleField = value; }
            }

            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string BarInterval
            {
                get { return this.barIntervalField; }
                set { this.barIntervalField = value; }
            }

            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string DSString
            {
                get { return this.dSStringField; }
                set { this.dSStringField = value; }
            }

            [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
            public string ProviderName
            {
                get { return this.providerNameField; }
                set { this.providerNameField = value; }
            }
        }
    }
}

Bottom line, use the code solutions xsd.exe generates from your XML data file as a guide, not a truth.最重要的是,使用从您的 XML 数据文件生成的代码解决方案 xsd.exe 作为指导,而不是事实。 It's a great tool, but needs to be used with a grain of salt.这是一个很棒的工具,但需要与一粒盐一起使用。 ... welcome your comments on my XMLdeserialization problem. ...欢迎您对我的 XML 反序列化问题发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 XML 反序列化 System.InvalidOperationException”<objects xmlns=""> 没想到</objects> - XML deserialization System.InvalidOperationException” the <Objects xmlns=''> was not expected 为什么我们的几个用户会收到“ System.InvalidOperationException: <html xmlns=''> 没想到。”? - Why are a couple of our users getting “System.InvalidOperationException: <html xmlns=''> was not expected.”? c#System.InvalidOperationException - c# System.InvalidOperationException C#WPF获取错误 - System.InvalidOperationException: - C# WPF Getting error - System.InvalidOperationException: 获取错误“System.InvalidOperationException。XML 文档 (1, 2) 中存在错误”。 在 C# 中反序列化期间 - Getting error "System.InvalidOperationException. There is an error in XML document (1, 2)." during Deserialization in C# C#中的XML反序列化错误-InvalidOperationException: <element xmlns='http://www.w3.org/2001/XMLSchema'> 没想到 - XML Deserialization Error in C# - InvalidOperationException: <element xmlns='http://www.w3.org/2001/XMLSchema'> was not expected c# wpf 错误 (System.InvalidOperationException) - c# wpf error (System.InvalidOperationException) C#WPF中的System.InvalidOperationException - System.InvalidOperationException in C# WPF C#XML:System.InvalidOperationException - C# XML: System.InvalidOperationException C#XML错误:System.InvalidOperationException - C# XML Error: System.InvalidOperationException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM