【问题标题】:How to Deserialize XML in C#如何在 C# 中反序列化 XML
【发布时间】:2019-11-16 20:29:58
【问题描述】:

我从这里复制了 xml 文档How to Deserialize XML document

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

我将该代码与从 /paste special/paste xml 生成的类一起用作类

using System;
using System.IO;
using System.Xml.Serialization;

namespace DeSerialize
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer serializer =
        new XmlSerializer(typeof(CarCollectionCar));

            // Declare an object variable of the type to be deserialized.
            CarCollectionCar i;

            using (Stream reader = new FileStream("cars.xml", FileMode.Open))
            {
                // Call the Deserialize method to restore the object's state.
                i = (CarCollectionCar)serializer.Deserialize(reader);
            }

            // Write out the properties of the object.
            Console.Write(
            // i.StockNumber + "\t" +
            i.StockNumber + "\t" +
            //i.StockNumber + "\t" +
            i.Model + "\t" +
            i.Make);


        }
    }


    [Serializable()]
    public partial class CarCollection
    {

        /// <remarks/>
        [XmlArrayItem("Car", IsNullable = false)]
        public CarCollectionCar[] Cars { get; set; }
    }

    /// <remarks/>
    [Serializable()]
    [System.ComponentModel.DesignerCategory("code")]
    [XmlType(AnonymousType = true)]
    public partial class CarCollectionCar
    {

        /// <remarks/>
        public ushort StockNumber { get; set; }

        /// <remarks/>
        public string Make { get; set; }

        /// <remarks/>
        public string Model { get; set; }
    }


}

我得到错误

Unhandled Exception: System.InvalidOperationException: There is an error in XML 
document (2, 2). ---> System.InvalidOperationException: <CarCollection xmlns=''> 
was not expected.
       at 
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderCarCollectionCar.Read3_CarCollectionCar()
       --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
   at DeSerialize.Program.Main(String[] args)

如何解决问题并输出所需的 Cars 参数?

【问题讨论】:

  • 这是一个专业提示。尝试先序列化您的课程。然后看看反序列化有什么问题。
  • new XmlSerializer(typeof(CarCollectionCar)); 应该是 new XmlSerializer(typeof(CarCollection));,因为您正在反序列化汽车集合,而不是单个汽车。

标签: c# xml serialization


【解决方案1】:

这是因为它无法理解您 XML 的第二行上的CarCollection

对象是CarCollection.Cars[Car]

最好的方法可能是构建一个汽车集合对象并将其序列化为 XML 并查看它从那里输出的内容。一旦您可以将其序列化为 xml,那么反序列化为对象就相当容易了。

或者您可以反序列化为动态 C# 对象并查看它构建的对象。

但是这段代码可以反序列化

此代码将在对象与 xml 匹配时起作用

class Program
{
    static void Main(string[] args)
    {
        XmlSerializer serializer =
    new XmlSerializer(typeof(CarCollection));

        // Declare an object variable of the type to be deserialized.
        CarCollection i;

        using (Stream reader = new FileStream("cars.xml", FileMode.Open))
        {
            // Call the Deserialize method to restore the object's state.
            i = (CarCollection)serializer.Deserialize(reader);
        }

        // Write out the properties of the object.
       // Console.Write(
        // i.StockNumber + "\t" +
       /// i.StockNumber + "\t" +
        //i.StockNumber + "\t" +
       // i.Model + "\t" +
       // i.Make);

    }
}

[Serializable()]
public partial class CarCollection
{

    /// <remarks/>
    [XmlArrayItem("Car", IsNullable = false)]
    public Car[] Cars { get; set; }
}

/// <remarks/>
[Serializable()]
[System.ComponentModel.DesignerCategory("code")]
[XmlType(AnonymousType = true)]
public partial class Car
{
    /// <remarks/>
    public ushort StockNumber { get; set; }

    /// <remarks/>
    public string Make { get; set; }

    /// <remarks/>
    public string Model { get; set; }
}

【讨论】:

  • 我无法反序列化,因为我已经使用 C# 工具反序列化了。我需要使用它而不是每天反序列化 1000 次。
猜你喜欢
  • 2015-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2010-11-25
相关资源
最近更新 更多