February 10, 2004

DevDays 2004 Israel

It's been Microsoft DevDays 2004 in Israel today. Well, DevDay actually. Here are the impressions I got there: One has to get up earlier to not miss the keynote. VS.NET has cool PocketPC emulator. Code Access Security is omnipotent. Lutz Roeder's .NET Reflector may hang out in the middle of ...

February 9, 2004

On Making XML Namespaced On The Fly

This interesting trick has been discussed in microsoft.public.dotnet.xml newsgroup recently. When one has a no-namespaced XML document, such as <?xml version="1.0"?> <foo> <bar>Blah</bar> </foo> there is a trick in .NET, which allows to read such document as if it has some default namespace: <?xml version="1.0"?> <foo xmlns="http://foo.com"> <bar>Blah</bar> </foo> ...

Actually I have no idea when this could be useful, but people keep asking if this can be done (I presume they are neglecting namespaces in fact, but still I think there are real use cases for such functionality). And while it's probably not 100% clean architecturally, there is an effectieve and simple way. The crux is to read XML document not as standalone document, but as XML fragment, providing XmlNamespaceManager with default namespace set up. Here is the code:

string xml = 
@"<?xml version=""1.0""?>
XmlNameTable nt = new NameTable();
XmlNamespaceManager nsm = new XmlNamespaceManager(nt);
nsm.AddNamespace(String.Empty, "http://foo.com");
XmlParserContext ctx = new XmlParserContext(nt, nsm, null, XmlSpace.Default);
XmlTextReader r = new XmlTextReader(xml, XmlNodeType.Document, ctx);
//Read it to XmlDocument to test
XmlDocument doc = new XmlDocument();
The result is
<?xml version="1.0"?>
<foo xmlns="http://foo.com">

I was quite surprised to see it works even when XML fragment type is XmlNodeType.Document, IMO it should work only for XmlNodeType.Element typed XML fragment. With XmlNodeType.Document it looks like inter-document namespace definition nonsense, but anyway, nice and effective trick.

Read more about reading XML fragments with XmlTextReader in MSDN.