Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlSerializer sample from MSDN fails

I am trying to learn how to use XMLSerializer. I created a VS2010 project using the sample code on: http://msdn.microsoft.com/en-us/library/tz8csy73(v=vs.100).aspx.

The code is supposed to deserialize a simple XML document into a simple C# object. It compiles and runs without error, but fails to restore the C# object. All fields remain either 0 or null.

I have .NET Framework 4.0 as required by the sample. I put a breakpoint on the last Console.Write and can see that all values are 0 or null.

like image 888
John Pankowicz Avatar asked Dec 06 '25 19:12

John Pankowicz


1 Answers

The problem is the XML file in the sample. The names of the elements are prefixed with an XML namespace and that's causing the serializer to not map them to the raw fields in the OrderedItem type. If you remove the namespaces in the XML file this sample will run correctly.

Alternatively you can decorate the OrderedItem type to contain the proper namespaces used in the simple.xml file

public class OrderedItem
{
    [XmlElement(Namespace = "http://www.cpandl.com")]
    public string ItemName;
    [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()
    {
        LineTotal = UnitPrice * Quantity;
    }
}
like image 165
JaredPar Avatar answered Dec 09 '25 08:12

JaredPar