Tech Off Thread

4 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Exception parsing web.config when specifying <configuration xmlns="...">

Back to Forum: Tech Off
  • User profile image
    mrichman

    I am parsing the value of my forms auth timeout in the /configuration/system.web/authentication/forms element of my web.config as follows:

    string webconfig = Request.ServerVariables["APPL_PHYSICAL_PATH"].ToString() + "web.config";
    System.Xml.XmlDocument x = new System.Xml.XmlDocument();
    x.Load(webconfig);
    System.Xml.XmlNode node = x.SelectSingleNode("/configuration/system.web/authentication/forms");
    int timeout = int.Parse(node.Attributes["timeout"].Value, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
    This code works fine, unless I specify a namespace for the <configuration> element:

    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

    In this case, SelectSingleNode() returns null. Omitting the xmlns="..." directive allows the code to work without an exception.

    What am I doing wrong?

    - Mark

  • User profile image
    mrichman

    I found an article online that explained it to me just as you posted. It works like a champ! Thanks a million.

    Too bad it just can't infer a namespace.

  • User profile image
    Sven Groot

    mrichman wrote:
    I found an article online that explained it to me just as you posted. It works like a champ! Thanks a million.

    Too bad it just can't infer a namespace.

    Iirc this is one of the things XPath 2.0 and XSLT 2.0 (because trust me, this limitation gets really annoying when you are writing an XSLT transformation) are supposed to fix, but neither is a recommendation yet so no telling when they'll be supported by MS.

  • User profile image
    Sven Groot

    When an element uses a non-default (empty) namespace, you must use a prefix in XPath queries even if the document doesn't define one.

    System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
    nsmgr.AddNamespace("c", "http://schemas.microsoft.com/.NetConfiguration/v2.0");

    System.Xml.XmlNode node = x.SelectSingleNode("/c:configuration/c:system.web/c:authentication/c:forms", nsmgr);

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.