如何反序列化XML属性到对象,然后遍历对象

时间:2018-10-15 14:07:05

标签: c# xml visual-studio xmlserializer

我希望能够“处理” XML文件中的“车辆”。理想情况下,我想遍历所有车辆并计算它们的价格,并更改它们是否为OnSale。然后,这些值将显示在UI中。我的代码反序列化了XML文件,但是我无法访问Vehicle的任何属性。我不需要将对象序列化回XML。

我试图用Console.WriteLine价格,但是当我运行代码时,它返回为0。是否应该创建一个ResponseGeographyVendorRegionVehicle数组?然后以某种方式将这种类型的对象添加到数组中?

这是XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<Response>
  <Geography>
    <Vendor id="JOHN">
      <Region id="1"></Region>
      <Region id="2">
        <Vehicle Make="HONDA" Fuel="Gas" Price="12000" OnSale="Y" Account="JOHNH" />
        <Vehicle Make="ACURA" Fuel="Gas" Price="14100" OnSale="Y" Account="JOHNH" />
        <Vehicle Make="TOYOTA" Fuel="Gas" Price="8000" OnSale="N" Account="JOHNH" />
        <Vehicle Make="HYUNDAI" Fuel="Gas" Price="13000" OnSale="Y" Account="JOHNH" />
        <Vehicle Make="INFINITY" Fuel="Gas" Price="16000" OnSale="N" Account="JOHNH" />
      </Region>
      <Region id="3"></Region>
      <Region id="4"></Region>
    </Vendor>
  </Geography>
</Response>

这是我的Program.cs:

namespace XMLDeserializeExample
{
    class Program 
    {
        static void Main(string[] args)
        {
            string path = @"c:\XMLFile1.xml";
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "Response";
            XmlSerializer ser = new XmlSerializer(typeof(ResponseGeographyVendorRegionVehicle), xRoot);
            ResponseGeographyVendorRegionVehicle i;
            using (Stream reader = new FileStream(path,FileMode.Open)) 
            {
                i = (ResponseGeographyVendorRegionVehicle)ser.Deserialize(reader);
                Console.WriteLine(i.Price);
                Console.ReadLine();
            }
        }

    }
}

这是创建的“粘贴特殊响应.CS”文件:

namespace XMLDeserializeExample
{
}

// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Response
{

    private ResponseGeography geographyField;

    /// <remarks/>
    public ResponseGeography Geography
    {
        get
        {
            return this.geographyField;
        }
        set
        {
            this.geographyField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeography
{

    private ResponseGeographyVendor vendorField;

    /// <remarks/>
    public ResponseGeographyVendor Vendor
    {
        get
        {
            return this.vendorField;
        }
        set
        {
            this.vendorField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeographyVendor
{

    private ResponseGeographyVendorRegion[] regionField;

    private string idField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Region")]
    public ResponseGeographyVendorRegion[] Region
    {
        get
        {
            return this.regionField;
        }
        set
        {
            this.regionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeographyVendorRegion
{

    private ResponseGeographyVendorRegionVehicle[] vehicleField;

    private byte idField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Vehicle")]
    public ResponseGeographyVendorRegionVehicle[] Vehicle
    {
        get
        {
            return this.vehicleField;
        }
        set
        {
            this.vehicleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeographyVendorRegionVehicle
{

    private string makeField;

    private string fuelField;

    private ushort priceField;

    private string onSaleField;

    private string accountField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Make
    {
        get
        {
            return this.makeField;
        }
        set
        {
            this.makeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Fuel
    {
        get
        {
            return this.fuelField;
        }
        set
        {
            this.fuelField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public ushort Price
    {
        get
        {
            return this.priceField;
        }
        set
        {
            this.priceField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string OnSale
    {
        get
        {
            return this.onSaleField;
        }
        set
        {
            this.onSaleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Account
    {
        get
        {
            return this.accountField;
        }
        set
        {
            this.accountField = value;
        }
    }
}

请让我知道如何更好地自我解释。道歉,如果这一切都没有道理-欢迎来到我的周末大声笑。

谢谢。

2 个答案:

答案 0 :(得分:2)

由于您的xml根目录显然是Response而不是ResponseGeographyVendor,因此您必须反序列化为该类型:

string path = @"c:\XMLFile1.xml";
XmlSerializer ser = new XmlSerializer(typeof(response);
ResponseGeographyVendor i;
using (Stream reader = new FileStream(path,FileMode.Open)) 
{
    i = ((Response)ser.Deserialize(reader)).Geography.Vendor;
    Console.WriteLine(i.Price);
    Console.ReadLine();
}

序列化程序仅适用于整个xml文档。您不能只是编写或阅读其中的一部分。因此,只需使用xml,将其序列化为Response的实例并获取其Geography成员即可。

现在,您可以轻松地在第二个Vehicle中获得第三个Region

var vehicle = i.Region[1].Vehicle[2];

请注意,您不需要自己提供xml-root。

答案 1 :(得分:1)

您将要使用.Net内置的XML序列化器。

首先创建一个代表XML文档数据的类:

public class Response
{
      public Geography Geography {get; set;}
}
public class Geography
{
       public Vendor Vendor{get;set;}
}
public class Vendor
{
      public List<Region> Regions {get;set;}
}
public class Region
{
}

,依此类推。 然后将xml作为字符串读取并反序列化:

string myXml = File.ReadAsStringAsync(filepath).Result;
XmlSerializer ser = new XmlSerializer(typeof(Response));
using (TextReader reader = new StringReader(myXml)
{
Response myResponse = ser.Deserialize(reader);
}

然后,您可以遍历地理对象上的所有属性和内容。