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

How to Deserialize XML Attributes into objects, then iterate through the objects

我希望能够 'do things' 到 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();
            }
        }

    }
}

这是创建的选择性粘贴 Response.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;
        }
    }
}

请告诉我如何更好地解释自己。抱歉,如果 none 有道理-欢迎来到我的周末哈哈。

谢谢。

您需要使用 .Net 中内置的 XML 序列化程序。

首先创建一个class来表示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);
}

然后您可以遍历 Geography 对象的所有属性和内容。

由于您的 xml-root 显然是 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-member.

现在您可以在第二个 Region:

内轻松获得第三个 Vehicle
var vehicle = i.Region[1].Vehicle[2];

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