InfoPath IXMLDOMDocument Reference to undeclared namespace prefixBy making use of the Microsoft Office Interop libraries it is possible to fill an InfoPath form automatically. This can be useful when you would like to run a large batch of initial settings.

Trying to set a query property in the DOM of a data source I received the error “Reference to undeclared namespace prefix: ‘tns'”. The reason of this error is that the xml contains multiple namespaces and that you have to explicitly define the namespace to use.

By default the DOM property you can access from the XDocument are of the type IXMLDOMDocument. But working with this type, does not allow you to set the required namespace for your selections. To get around the issue convert the IXMLDOMDocument to a IXMLDOMDocument2 which makes it possible to define a “SelectionNamespaces” property. If you fill this property with the required documentElement’s namespace, the xpath selection of your node will succeed and the error is gone.

Below is an example of the Data source’s IXMLDOMDocument2 content (xml) and some demo code to select the required node.

IXMLDOMDocument2 content

<dfs:myFields xmlns:dfs=”
dataFormSolution” xmlns:tns=”” xmlns:my=”
2007-09-05T13:53:48″ xmlns:_xdns0=”
changeTracking” xmlns:soap=”” xmlns:xsi=”
XMLSchema-instance” xmlns:xsd=”” xmlns:diffgr=”urn:schemas-microsoft-com:
xml-diffgram-v1″ xmlns:msdata=”urn:schemas-microsoft-com:xml-msdata”>

Example code

private static void DemoCode()
 //Start application and load the xsn file
 Application application = new ApplicationClass();
 XDocument document = application.XDocuments.NewFromSolution(“c:test.xsn”);

 //Get the XML Document Object Model of the webservice datasource
 //and load/convert the type IXMLDOMDocument as IXMLDOMDocument2
 IXMLDOMDocument2 docDom = document.DataObjects[“WebService_SearchEmployee”].DOM as IXMLDOMDocument2;

 //retrieve the namespace and set the SelectionNamespaces property
 string tsnNamespace = GetTNSNamespace(docDom);
 docDom.setProperty(“SelectionNamespaces”, tsnNamespace);

 //Get the required node
 IXMLDOMNode nodeEmployeeName = docDom.selectSingleNode(“//tns:name”);

private static string GetTNSNamespace(IXMLdocDomument2 xmlDoc)
 return xmlDoc.documentElement.attributes.getNamedItem(“xmlns:tns”).xml;