Search code examples
c#namespaceslinq-to-xmlxelement

Change/rename namespace prefix


I have an XELEMENT that contains these elements

<customer>
    <ns8:title xmlns:ns8="http://ws.xxx.com/xxx/model/common">B< /ns8:title>
    <ns9:firstname xmlns:ns9="http://ws.xxx.com/xxx/model/common">Bob< /ns9:firstname>
    <ns10:lastname xmlns:ns10="http://ws.xxx.com/xxx/model/common">Petier< /ns10:lastname>
    <ns11:bday xmlns:ns11="http://ws.xxx.com/xxx/model/common">19310227< /ns11:bday>
    <ns12:rank xmlns:ns12="http://ws.xxx.com/xxx/model/common">1< /ns12:rank>
</customer>

I would like to transform the prefix like this.

<customer>
    <ns1:title xmlns:ns1="http://ws.xxx.com/xxx/model/common">B< /ns1:title>
    <ns2:firstname xmlns:ns2="http://ws.xxx.com/xxx/model/common">Bob< /ns2:firstname>
    <ns3:lastname xmlns:ns3="http://ws.xxx.com/xxx/model/common">Petier< /ns3:lastname>
    <ns4:bday xmlns:ns4="http://ws.xxx.com/xxx/model/common">19310227< /ns4:bday>
    <ns5:rank xmlns:ns5="http://ws.xxx.com/xxx/model/common">1< /ns5:rank>
< /customer>

I tried to remove the attributes but with no luck..

Any idea?


Solution

  • You should remove the existing namespace definition attribute (if there is any) and add a new one:

    element.Add(new XAttribute(XNamespace.Xmlns + "ns1", "http://ws.xxx.com/xxx/model/common"));
    

    By adding an explicit namespace attribute you will force the XElement to use it for serializing.