简体   繁体   English

如何在 C# 中反序列化 XML

[英]How to Deserialize XML in C#

I have xml document copied from here How to Deserialize XML document我有从这里复制的 xml 文档如何反序列化 XML 文档

<?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>

I use that code with class generated from /paste special/paste xml as classes我将该代码与从 /paste special/paste xml 生成的 class 作为类一起使用

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; }
    }


}

I get error我收到错误

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)

How to resolve problem and output needed Cars params?如何解决问题和 output 需要汽车参数?

It's because it can't understand CarCollection on line two of your XML.这是因为它无法理解CarCollection行的 CarCollection。

Object is CarCollection.Cars[Car] Object 是CarCollection.Cars[Car]

Best way might be to build an object of car collections and serialise this into XML and see what it outputs from there.最好的方法可能是构建汽车 collections 的 object 并将其序列化为 XML 并查看它从那里输出的内容。 Once you can serialise it to xml then deserialising into objects is fairly easy.一旦你可以将它序列化为 xml 然后反序列化为对象就相当容易了。

Or you could deserialise into a dynamic C# object and see what object it builds.或者您可以反序列化为动态 C# object 并查看它构建的 object。

But this code will work to deserialise但是这段代码可以反序列化

This code will work though as objects match the xml此代码将有效,因为对象匹配 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; }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM