Infopath forms and the XmlNamespaceManager


One common task when programmatically manipulating an InfoPath form is setting up the namespace manager.  The following code will fail:    MyInfopathDOM.SelectSingleNode("//my:name");  because of the unrecognized "my" prefix.  But create a namespacemanager with the namespaces used in the form and you are good to go: MyInfopathDOM.SelectSingleNode("//my:name",myNamespaceManager);

Luckily, Infopath lists all the required namespaces in one place: the documentElement. For example:

<?xml version="1.0" encoding="UTF-8"?>
<?mso-infoPathSolution solutionVersion="1.0.0.136" productVersion="11.0.6162" PIVersion="1.0.0.0" href="..
" name=".." ?>
<?mso-application progid="InfoPath.Document"?>
<my:FormData xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:s0="http://microsoft.com/Biztalk2004/Hws/Hwsservice" xmlns:s1="http://microsoft.com/wsdl/types/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:ns1="http://schemas.xmlsoap.org/wsdl/" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2004-06-02T22-26-23" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-us">
  <my:RequestInfo>
    <my:InitiatorName>me</my:InitiatorName>
    ......

The following is a code snippet which scans the form's documentElement and initializes an XmlNamespaceManager instance with all the required namespaces.

   public  XmlNamespaceManager InitNamespaceManager(XmlDocument xmlDOMDoc)
  {
        XmlNamespaceManager                 xnmMan;

        xnmMan = new XmlNamespaceManager(xmlDOMDoc.NameTable);

        foreach (XmlAttribute nsAttr in xmlDOMDoc.DocumentElement.Attributes)

        {

              if (nsAttr.Prefix=="xmlns")

                    xnmMan.AddNamespace(nsAttr.LocalName,nsAttr.Value);

        }

        return xnmMan;

  }

As with any code sample: No warranty is implied, Use at your own risk, Not suitable for children under three years old, etc 🙂

Skip to main content