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="" productVersion="11.0.6162" PIVersion="" href=".." name=".." ?>
<?mso-application progid="InfoPath.Document"?>
<my:FormData xmlns:xsi="" xmlns:xhtml="" xmlns:dfs="" xmlns:s0="" xmlns:s1="" xmlns:mime="" xmlns:tm="" xmlns:soapenc="" xmlns:soap="" xmlns:http="" xmlns:ns1="" xmlns:my="" xmlns:xd="" xml:lang="en-us">

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")



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