Abhimanyu
Abhimanyu

Reputation: 423

XML Parsing Error: not well-formed

when i am trying to open a page in sharepoint the above error is appearing. actually i used the following code :

protected void Page_Load(object sender, EventArgs e)
{
    Response.ContentType = "text/xml";
    Response.Write(GenerateTagCloud());
    Response.End();       
}

private string GenerateTagCloud()
{
    SPWeb myweb = null;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        SPSite mysite1 = new SPSite(mysite.ID);
        myweb = mysite1.OpenWeb();
    });

    myweb.AllowUnsafeUpdates = true;

    SPList categories = myweb.Lists["Discussion Categories"];
    SPList discussion = myweb.Lists["Team Discussion"];

    System.Text.StringBuilder sp = new System.Text.StringBuilder();
    //System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

    sp.Append("<?xml version='1.0' encoding='UTF-8'?>");
    sp.Append("<tags>");

    foreach (SPListItem category in categories.Items)
    {            
        string categoryname = category.Name;
        categoryname = categoryname.Replace(" ", "%20");
        sp.Append("<a href='" + myweb.Url + "/Pages/Home.aspx?Discussion=" + categoryname + "' style='font-size: 13.5pt'  color='0x7b7b7b'>" + category.Name + "</a>");
    }
    sp.Append("</tags>");

    myweb.AllowUnsafeUpdates = false;
    return sp.ToString();

}

but in the output it shows as : tag opening and closing of the tags node in &lt and &gt . how to correct this?

Upvotes: 0

Views: 952

Answers (1)

Oded
Oded

Reputation: 498992

Since the issue is with a & in one of the category names, all you need to do is escape it - there are five characters that need to be escaped in XML:

  • & - &amp;
  • < - &lt;
    • &gt;
  • " - &quot;
  • ' - &apos;

In the case of &, simply replace it with &amp;.

Having said that, if you are writing XML you should be using an XmlWriter and not a StringBuilder - this will escape the characters correctly and this kind of error will not occur:

XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data & data");
writer.WriteEndElement();

Code taken from here.

Upvotes: 1

Related Questions