Wednesday, November 20, 2013

SharePoint field + XML = Blank field

Intro:
I've been tasked with storing the contents of an RSS feed (xml) to SharePoint via a Custom Timer Job.

When I tried to run the following code. I simply got a blank field for the "RSSContents" field of the new item.

using (System.Net.WebClient client = new System.Net.WebClient())
{
using (Stream data = client.OpenRead("http://www.bom.gov.au/fwo/IDZ00059.warnings_vic.xml"))
{
using (StreamReader reader = new StreamReader(data))
{
    SPWebApplication webApp = this.Parent as SPWebApplication;
    SPList list = webApp.Sites[0].RootWeb.Lists["TimerTest"];
    SPListItem newListItem = list.Items.Add();
    newListItem["Title"] = DateTime.Now.ToString();
    string s = reader.ReadToEnd();
    newListItem["RSSContents"] = s;
    newListItem.Update();
}
}
}

Workaround:
Add HtmlEncode into the mix:
using (System.Net.WebClient client = new System.Net.WebClient())
{
using (Stream data = client.OpenRead("http://www.bom.gov.au/fwo/IDZ00059.warnings_vic.xml"))
{
using (StreamReader reader = new StreamReader(data))
{
    SPWebApplication webApp = this.Parent as SPWebApplication;
    SPList list = webApp.Sites[0].RootWeb.Lists["TimerTest"];
    SPListItem newListItem = list.Items.Add();
    newListItem["Title"] = DateTime.Now.ToString();
    string s = reader.ReadToEnd();
    s = WebUtility.HtmlEncode(s);
    newListItem["RSSContents"] = s;
    newListItem.Update();
}
}
}

I'm working in a SharePoint 2013 environment. So your results may vary. But I suspect this is the same across each of the different SharePoint versions. 

No comments:

Post a Comment