Search code examples
c#xmlxmlwriter

XML Parsing Error: not well-formed error


I am trying to parse my database feed data as XML, however on the client side I am keep getting this error:

XML Parsing Error: not well-formed
Location: http://localhost:12736/Test.aspx
Line Number 7, Column 26:        

 <Publication Date>29/04/2015 09:40:53</Publication Date>
 ------------------^

I have tried converting the datetime parameter 'ActivateDate' into string, but I am still getting the same error on the 'publication date' node. I have also tried looking online for a solution but I am still unable to solve this.

Here is my server code for further reference:

        Response.Clear();
        Response.ContentType = "text/xml";
        using (XmlTextWriter xml = new XmlTextWriter(Response.OutputStream, Encoding.UTF8))
        {
            xml.Formatting = Formatting.Indented;
            xml.Indentation = 4;
            xml.WriteStartDocument();
            xml.WriteStartElement("items");

            foreach (DataRow oFeedItem in dt.Rows)
            {

               // DateTime dtt = DateTime.Parse(oFeedItem["ACTIVEDATE"].ToString());

                string dat = Convert.ToString(oFeedItem["ACTIVEDATE"].ToString()); 

               // dat.ToString("dd MMMM yyyy"); 
                xml.WriteStartElement("Article");
                xml.WriteElementString("title", oFeedItem["title"].ToString());
                xml.WriteStartElement("description");
                xml.WriteCData(oFeedItem["Body"].ToString());
                xml.WriteEndElement();
                xml.WriteElementString("categories", oFeedItem["categories"].ToString());
                xml.WriteElementString("Publication Date", dat);
                xml.WriteEndElement();
            }

            xml.WriteEndElement();
            xml.WriteEndDocument();
            xml.Flush();
            xml.Close();

            Response.End();

        }

Thank you for your suggestion and feedback.


Solution

  • XML element names can't contain spaces.

    W3C specification declares xml tag as:

    '<' Name (S Attribute)* S? '>'
    

    where S is one or more whitespace characters (#x20 | #x9 | #xD | #xA).

    So from this specification it is clearly seen that space (#x20) considered as delimiter between element name and attributes list - so name itself can't contain spaces.

    Changing your element Publication Date name to Publication_Date will help to make your xml well-formed.

    xml.WriteElementString("Publication_Date", dat);