views:

326

answers:

1

Lets say I have the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<Customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
    <Customer>
     <FirstName></FirstName>
     <LastName></LastName>
    </Customer>
    <Customer>
     <FirstName></FirstName>
     <LastName></LastName>
    </Customer>
    <Customer>
     <FirstName></FirstName>
     <LastName></LastName>
    </Customer>
</Customer>

I have also created a Customer object that maps to the appropriate fields.

Now if I try to serialize this to a generic list as such:

XmlSerializer xml = new XmlSerializer(typeof(List<Customer>));

I'll get an exception, because my List is not mapped to the same namespace as the Customers in the XML doc, and I can't add it as an attribute because I'm using a generic list, not a custom collection

How can I tell the serializer to match up the namespace to the list without creating a custom collection?

Edit: I should elaborate a little, the exception thrown by the serializer is:

(Customers xmlns=''> was not expected.

Now because I'm using a List(T) as the parent node, how can I match up the generic list to the namespace specified in the XML document?

+1  A: 

I think the error has to do with the <Customers> node not the xmlns.

Try

XmlRootAttribute xr = new XmlRootAttribute("Customers");
XmlSerializer xs = new XmlSerializer(typeof(List<Customer>), xr);

By default it would expect an <ArrayOfCustomer> node

Jeff Hall
Perfect, thanks!
jacko