如何反序列化 XML 数组?

How to deserialize XML array?

我有一个 MVC 控制器,它的 Get() 方法 returns 一个格式良好的订单列表 XML。 XML 可以被在线 XML 解析器很好地解析。 但是,XML 的根元素对我来说是未知的:<ArrayOfOrder>。而且我不知道如何使用 XmlSerializer 在我的 C# 应用程序中进行解析。 XML 的根目录如下所示:

<ArrayOfOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

如何用 XmlSerializer 反序列化它?

假设你想反序列化为一个对象,你可以尝试这样的事情:

using System.Xml.Serialization;

// This is the class that will be deserialized.
public class OrderedItem
{
    [XmlElement(Namespace = "http://www.cpandl.com")] 
    public string ItemName; //change "http://www.cpandl.com" or 
                            //"http://www.cpandl.com" to your own xmlns adresses
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string Description;
    [XmlElement(Namespace="http://www.cohowinery.com")]
    public decimal UnitPrice;
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public int Quantity;
    [XmlElement(Namespace="http://www.cohowinery.com")]
    public decimal LineTotal;
    // A custom method used to calculate price per item.
    public void Calculate() //an example method
    {
        LineTotal = UnitPrice * Quantity;
    }
}
public class Test
{
 public static void Main()
{
    Test t = new Test();
    // Read a purchase order.
    t.DeserializeObject("simple.xml"); 
    //change "simple.xml" to your own xml file
}

private void DeserializeObject(string filename)
{
    Console.WriteLine("Reading with Stream");
    // Create an instance of the XmlSerializer
    XmlSerializer serializer =
    new XmlSerializer(typeof(OrderedItem));

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

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

    // Write out the properties of the object
    // Change the variables (itemname, description, unitprice etc) to your own 
    Console.Write(
    i.ItemName + "\t" +
    i.Description + "\t" +
    i.UnitPrice + "\t" +
    i.Quantity + "\t" +
    i.LineTotal);
  }
}

本例中的XML:

<?xml version="1.0"?>
  <OrderedItem xmlns:inventory="http://www.cpandl.com" 
  xmlns:money="http://www.cohowinery.com">
  <inventory:ItemName>Widget</inventory:ItemName>
  <inventory:Description>Regular Widget</inventory:Description>
  <money:UnitPrice>2.3</money:UnitPrice>
  <inventory:Quantity>10</inventory:Quantity>
  <money:LineTotal>23</money:LineTotal>
</OrderedItem>

我不知道你的其他内容 XML,但这是它的基本要点。