BizTalk Utilities CV ,   Jobs ,   Code library
 
Go to the front page to continue learning about XML or select below:

Contents

ReBlogger Contents

Previous posts in SQLXML

 
 
Page 5803 of 19542

Dynamically Getting Namespaces in an XML

Blogger : MSDN Blogs
All posts : All posts by MSDN Blogs
Category : SQLXML
Blogged date : 2007 Dec 28

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. :)


Read comments or post a reply to : Dynamically Getting Namespaces in an XML
Page 5803 of 19542

Newest posts
 

    Email TopXML