簡體   English   中英

如何反序列化 XML 陣列?

[英]How to deserialize XML array?

我有一個 MVC controller,它的 Get() 方法返回一個訂單列表作為格式正確的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反序列化它?

假設您想反序列化為 object,您可以嘗試以下操作:

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 的 rest,但這是它的基本要點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM