Share via


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="https://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="https://www.w3.org/1999/xhtml" xmlns:dfs="https://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:s0="https://microsoft.com/Biztalk2004/Hws/Hwsservice" xmlns:s1="https://microsoft.com/wsdl/types/" xmlns:mime="https://schemas.xmlsoap.org/wsdl/mime/" xmlns:tm="https://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="https://schemas.xmlsoap.org/soap/encoding/" xmlns:soap="https://schemas.xmlsoap.org/wsdl/soap/" xmlns:http="https://schemas.xmlsoap.org/wsdl/http/" xmlns:ns1="https://schemas.xmlsoap.org/wsdl/" xmlns:my="https://schemas.microsoft.com/office/infopath/2003/myXSD/2004-06-02T22-26-23" xmlns:xd="https://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 :)

Comments