15 August 2012

How do I – Programmatically select a field inside InfoPath XML using C#

As we know, InfoPath forms are actually XML documents behind the scenes… a special kind of XML, but XML nonetheless. As such we should be able to figure out how to change the value of a field pretty easily, right? You’d think so, but unless you live inside XML every day (so few of us do these days) it might now be as easy as you’d have thought. After getting the InfoPath document loaded to an XmlDocument object, one would expect a statement thus:
doc.SelectSingleNode("//my:Family", nsm).InnerText = "New Value";
to have the desired effect. Alas, it’s not that simple. It never is, is it? Smile Instead, this is what you’re greeted with:

What we need to do is ensure that your XmlNamespaceManager is properly assigned with the content from the given InfoPath form in order to translate the “my:” part of our xPath statement. If we take a look at the InfoPath document’s OuterXml value we see this:Untitled-1With so many xmlns attributes in the InfoPath document, we need some automation to prepare our XmlNamespaceManager so we can interact with the data properly. Adding this little code snippet to our existing code, should resolve that nasty error:

foreach (XmlAttribute att in doc.DocumentElement.Attributes)
  if (att.Prefix == "xmlns")
    nsm.AddNamespace(att.LocalName, att.Value);

Remember to create the XmlNamespaceManager object with a reference to the base XmlDocument’s NameTable thus:

nsm = new XmlNamespaceManager(doc.NameTable);
Throw all that together and we are now able to manipulate the InfoPath field programmatically to our heart’s content.


No comments:

Post a Comment

Comments are moderated only for the purpose of keeping pesky spammers at bay.

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...