I recently had a requirement to extract some information from a InfoPath XML form stored in a SharePoint library and show it in an external application.
The problem here was that we were using infopath forms services. and every time I tried to open up the XML file from code i would get a redirection error. GRRRRR….
Obviously, using the SharePoint OM would be the the quickest way for this, but it this app was not going to be run on the server.
The trick to this is to append this “?noredirect=true” without the quotes, to the URL that is your xm file. For example
This would would force a redirect to the forms services and show the browser enabled form
http://johndev/training/myform1.xml
However, this will for the file to no be redirected and opened up in its native application or in our case an XML document.
http://johndev/training/myform1.xml?noredirect=true
Here is the following C# code that shows how to open and read an IP form using straight XML objects
The basic code here does the following
1) Creates a Web Client object
2) Sets credentials on the Web Client Object
3) Open the InfoPath Form XML file with the xmlresolver object.
4) Perform standard XPath query to get the information
StringBuilder oBuilder = new StringBuilder();
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(oBuilder);
System.Xml.XmlTextWriter oXmlWriter = new System.Xml.XmlTextWriter(oStringWriter);
oXmlWriter.Formatting = System.Xml.Formatting.Indented;
#region UnComment this if you would like to use specific credentials
//System.Net.CredentialCache mycache = new System.Net.CredentialCache();
//mycache.Add(new Uri(@"http://[yoursite]"),"NTLM",new System.Net.NetworkCredential("user1", "pass", "johndev"));
//System.Net.WebClient _wc = new System.Net.WebClient();
//_wc.Credentials = mycache;
//_wc.Credentials = System.Net.CrendentialCache.DefaultCredentials;
#endregion
System.IO.Stream s = _wc.OpenRead(@"http://[yoursite]/[yourlibrary]/thisshouldbeyourform.xml?noredirect=true");
System.IO.StreamReader _xmlFile = new System.IO.StreamReader(s);
string _content = _xmlFile.ReadToEnd();
System.Xml.XmlDocument _doc = new System.Xml.XmlDocument();
_doc.LoadXml(_content);
System.Xml.XPath.XPathNavigator navigator = _doc.CreateNavigator();
System.Xml.XmlNamespaceManager manager = new System.Xml.XmlNamespaceManager(navigator.NameTable);
manager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2004-11-22T15:09:37");
System.Xml.XmlNode _node= _doc.SelectSingleNode("/my:myFields/my:[youfieldonform]", manager);
if (_node= != null)
{
Console.WriteLine(_node.InnerText);
}