Home > database >  How to deserialize XML array?
How to deserialize XML array?

Time:01-26

I have a MVC controller, its Get() method returns a list of Orders as a well-formed XML. That XML can be nicely parsed by online XML parsers. However, XML's root element is unknown to me: <ArrayOfOrder>. And I don't know how to parse in my C# app, using XmlSerializer. XML's root looks like this:

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

How can I deserialize it with XmlSerializer?

CodePudding user response:

Assuming you want to deserialize into an object, you could try something like this:

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

The XML in this example:

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

I don't know the rest of your XML, but that's the basic gist of it.

  •  Tags:  
  • Related