How to serialize XML to a shared collection when specifying a namespace

Suppose 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 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 am getting an exception because my list is not mapped to the same namespace as Clients in the XML document and I cannot add it as an attribute because I am using a generic list and not a custom collection

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

Edit: I have to elaborate a little, the exception thrown by the serializer:

(Clients xmlns = ''> did not expect.

Now, since I am using List (T) as the parent node, how can I map the generic list to the namespace specified in the XML document?

+1


source to share


1 answer


I think the error is related to <Customers> node not xmlns.

Try



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

      

By default, it expects the <ArrayOfCustomer> node

+1


source







All Articles