Reputation: 59
I have a weird problem. i have this Xml
<?xml version="1.0" encoding="utf-8"?>
<Facilities RunTime="2016-03-09 14:18:11">
<Facility ID="789">
<Name>Facility 4</Name>
<Contact />
<AreaName>Center</AreaName>
<MunicipalCode>453</MunicipalCode>
<SMSInfo />
<Materials />
</Facility>
<Facility ID="-1">
<Name>Facility 2</Name>
<Contact />
<AreaName>Mark</AreaName>
<MunicipalCode />
<SMSInfo />
<Materials />
</Facility>
</Facilities>
When i try to deserialize this xml, it fails on on tag <MunicipalCode />
when its empty (see the element MunicipalCode in the second root Facility)
but not on <MunicipalCode>453</MunicipalCode>
(in the first root) so when i change the empty one to <MunicipalCode>test test </MunicipalCode>
then it doesnt fail
this is my model, and i have tried to handle this value in case it comes as null.
[Table("FacilityNew")]
public class FacilityNew
{
[XmlAttribute("ID"), Key]
public int Id { get; set; }
[XmlElement("SMSInfo")]
public virtual SMSInfo smsInfos { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Contact")]
public string Contact { get; set; }
[XmlElement("AreaName")]
public string AreaNameID { get; set; }
[XmlIgnore]
public string MunicipalCode { get; set; }
[XmlElement("MunicipalCode")]
[Browsable(false)] // not displayed in grids
[EditorBrowsable(EditorBrowsableState.Never)] // not displayed by intellisense
public string MunicipalCodeStirng
{
get
{
if ((MunicipalCode) != null)
{
return MunicipalCode;
}
else
return "";
}
set
{
if ((value)!=null)
{
MunicipalCode = value;
}
else
{
MunicipalCode = "";
}
}
}
[XmlArray("Materials")]
[XmlArrayItem("Material")]
public virtual List<Material> Materials { get; set; }
public FacilityNew()
{
this.Materials = new List<Material>();
}
}
but it still fails
its weird because the other empty tags doesn't fail, and i got "input string was not in a correct format " and if i change the name of this tag to <MunicipalCodeASDF />
or something else, it doesn't fail.
this is how i deserialize,
XmlSerializer deserializer = new XmlSerializer(typeof(FacilityNew));
StreamReader sr = new StreamReader(path);
allaFacilities = (FacilityNew)deserializer.Deserialize(sr);
what is the problem
Upvotes: 0
Views: 2889
Reputation: 59
the problem is solved by adding a regex inside the deserializer
public static T Deserialize<T>(string xml){
XmlSerializer xs = new XmlSerializer(typeof(T));
string cleanXml = Regex.Replace(xml, @"<[a-zA-Z].[^(><.)]+/>",
new MatchEvaluator(RemoveText));
MemoryStream memoryStream = new MemoryStream((new UTF8Encoding()).GetBytes(cleanXml));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return (T)xs.Deserialize(memoryStream);
}
static string RemoveText(Match m) { return "";}
Upvotes: 1