Linq to Xml : Exception -The ' ' character, hexadecimal value 0x20, cannot be included in a name

MSanika picture MSanika · Jan 16, 2014 · Viewed 37k times · Source

This is my Entity Class with an Entity :

[Table(Name = "CLINICAL_ITEM_MASTER")]
public class ClinicalItemMaster
{
    [Column]
    public int CLIENT_INPUT_MHS_ID { get; set; }
    [Column]
    public Guid CLIENT_INPUT_MHS_GUID { get; set; }
    [Column]
    public string ITEM { get; set; }
    [Column]
    public int ITEM_ID { get; set; }
    [Column]
    public string ITEM_NUMBER { get; set; }
    [Column]
    public string CATEGORY { get; set; }
    [Column]
    public string DESCRIPTION { get; set; }       
    [Column]
    public DateTime? CREATE_DTTM { get; set; }
    [Column]
    public DateTime? UPDATE_DTTM { get; set; }
}

And Here I am accessing that Database Table data using Linq to XML(SQL) approach :

private XElement GetClinicalItemMaster()
{
    try
    {
        using (MyDatabase db = new MyDatabase())
        {
            return new XElement("CLINICALITEMMASTER",
                   from cim in db.TblClinicalItemMaster                           
                   select new XElement("Record",
                       new XElement("CLIENT_INPUT_MHS_ID", cim.CLIENT_INPUT_MHS_ID),
                       new XElement("CLIENT_INPUT_MHS_GUID", cim.CLIENT_INPUT_MHS_GUID.ToString()),
                       new XElement("ITEM ", cim.ITEM),
                       new XElement("ITEM_ID ", cim.ITEM_ID),
                       new XElement("ITEM_NUMBER ", cim.ITEM_NUMBER.ToString()),
                       new XElement("CATEGORY ", cim.CATEGORY.ToString()),
                       new XElement("DESCRIPTION ", cim.DESCRIPTION),
                       new XElement("MFG_CODE ", cim.MFG_CODE)      ));
        }

But here I am getting this error:

The '[white space]' character, hexadecimal value 0x20, cannot be included in a name.

The column is cim.ITEM, as per my analysis its a Non-Nullable column but While getting data from DataBase getting Null(The data per this column is Null)

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Jan 16, 2014

You have white spaces in elements names, which is not allowed in XML:

new XElement("ITEM ", cim.ITEM), // starting from this element
//                ^ here

Remove white spaces in order to make element names valid. BTW it's completely OK to have null as element value.