Welcome to MSDN Blogs Sign in | Join | Help

Dynamically Getting Namespaces in an XML

I have a utility that process XML files, ideally, I would like to be able to feed XQueries into the application, the problem was, the xml files have namespaces. So far, all examples on how to use XQuery with XmlNamespaceManager requires hard coded namespace, that means I need to know the URI and the prefix. Well, I would like to be able to dynamically get the namespaces.

I came up with this solution, this method will return an instance of XmlNamespaceManager with a specified XmlNameTable. Unfortunately, XPath 1.0 does not support default namespace, the default namespace will have 'default' prefix.

using System.Xml;
using System.Xml.XPath;

/// <summary>
/// Returns an instance of XmlNamespaceManager with a specified XmlDocument.NameTable.  
/// Returns null if no namespace is defined.
/// </summary>
/// <param name="Doc">The XmlDocument</param>
/// <returns>XmlNamespaceManager if there is at least one namespace, null if there is no namespace defined.</returns>
public XmlNamespaceManager CreateNamespaceManager(XmlDocument Doc)
{
    //Create an instance of XPathNavigator at the root of the XmlDocument.
    XPathNavigator Nav = Doc.SelectSingleNode("/*").CreateNavigator();
    XmlNamespaceManager Result = null;

    //Move to the first namespace.
    if (Nav.MoveToFirstNamespace())
    {
        Result = new XmlNamespaceManager(Doc.NameTable);

        do
        {
            //Add namespaces to XmlNamespaceManager, if the Nav.Name is an empty string, it is the default
            //namespace.  Assign 'default' as the prefix.
            Result.AddNamespace(String.IsNullOrEmpty(Nav.Name)? "default" : Nav.Name, Nav.Value);
        } while (Nav.MoveToNextNamespace());
    }

    return Result;
}

The XmlNamespaceManager now is generated dynamically, without having to know all namespaces in advance. This gave me the ability to change the XQueries, feed it at runtime to my application without having to recompile the app. I wish XPath 1.0 supports default namespace, it if is, it will be even simpler.

Hope this helps someone. :)

Published Friday, December 28, 2007 9:45 PM by HelloWorld
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Geek Lectures - Things geeks should know about &raquo; Blog Archive &raquo; Dynamically Getting Namespaces in an XML

# re: Dynamically Getting Namespaces in an XML

I love the post title, extracted from "Jerry McGuire" (I don't know how is it written).

In addition the content is also really cool ;)

Wednesday, March 25, 2009 11:40 AM by Moi

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker