Connecting Tech Pros Worldwide Forums | Help | Site Map

deserialising xml files with no namespace

=?Utf-8?B?SWFpbg==?=
Guest
 
Posts: n/a
#1: Jun 27 '08
I've created some c# classes from Xsds.

The classes have namespace attributes in the XmlRootAttributes.

Accordingly, they will NOT deserialize with the XmlSerializer unless the
same namespace is defined.

I've prepared a temporary fix by loading the xml as an XmlDocument, amending
the first element to include the namespace, serialising this to a string and
deserialising to my classes.

But surely there is an easier way....

Iain

Martin Honnen
Guest
 
Posts: n/a
#2: Jun 27 '08

re: deserialising xml files with no namespace


Iain wrote:
Quote:
I've created some c# classes from Xsds.
>
The classes have namespace attributes in the XmlRootAttributes.
>
Accordingly, they will NOT deserialize with the XmlSerializer unless the
same namespace is defined.
>
I've prepared a temporary fix by loading the xml as an XmlDocument, amending
the first element to include the namespace, serialising this to a string and
deserialising to my classes.
>
But surely there is an easier way....
Well the easiest way is to change the XmlRootAttribute.
If you can't do that then using an XmlParserContext as follows does work
for me:

string xml = "<Foo><Bar>baz</Bar></Foo>";
XmlSerializer ser = new XmlSerializer(typeof(Foo));

NameTable nt = new NameTable();
XmlNamespaceManager mgr = new XmlNamespaceManager(nt);
mgr.AddNamespace("", "http://example.com/2008/ns1");
XmlParserContext ctxt = new XmlParserContext(nt, mgr, "",
XmlSpace.Default);

Foo foo = (Foo)ser.Deserialize(XmlReader.Create(new
StringReader(xml), null, ctxt));
Console.WriteLine("foo.Bar: {0}", foo.Bar);

where the Foo class is defined as follows:

[XmlRoot(Namespace = "http://example.com/2008/ns1")]
public class Foo
{
public string Bar { get; set; }
}


--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Joe Fawcett
Guest
 
Posts: n/a
#3: Jun 27 '08

re: deserialising xml files with no namespace


"Iain" <Iain@discussions.microsoft.comwrote in message
news:D567B0A2-F2C7-47D9-9CAB-E3448349B00A@microsoft.com...
Quote:
I've created some c# classes from Xsds.
>
The classes have namespace attributes in the XmlRootAttributes.
>
Accordingly, they will NOT deserialize with the XmlSerializer unless the
same namespace is defined.
>
I've prepared a temporary fix by loading the xml as an XmlDocument,
amending
the first element to include the namespace, serialising this to a string
and
deserialising to my classes.
>
But surely there is an easier way....
>
Iain
As well as Martin's suggestion why does the XML to be deserialised not have
the namespaced elements?

--

Joe Fawcett (MVP - XML)

http://joe.fawcett.name


Closed Thread