Remove empty xml tag from ASP Net Web API POST Request

310 Views Asked by At

I want to remove the empty XML tag from XML-based POST Request in ASP.NET Core WEB API. Empty XML tag troubled me to deserialize XML to Model using XmlSerializerFormatters.

<?xml version = "1.0" encoding="UTF-8"?>
<DetailAssessmentRequest>
    <CaseId></CaseId>
    ...

    <LeisureTimeActivities>
        <LeisureTimeActivity>1</LeisureTimeActivity>
        <LeisureTimeActivity/>  //want to remove this
        <LeisureTimeActivity>2</LeisureTimeActivity>
        <LeisureTimeActivity/>  //want to remove this
    </LeisureTimeActivities>
    <LeisureTimeActivityOthers></LeisureTimeActivityOthers>  //want to remove this
    ...

    <Observation>Comments</Observation>
</DetailAssessmentRequest>

I have already added XmlSerializerFormatters and XmlDataContractSerializerFormatters in my Startup.cs

services.AddMvc()
     .AddXmlSerializerFormatters()
     .AddXmlDataContractSerializerFormatters();

Here is my Model:

[Serializable]
public class DetailAssessmentRequest
{ 
    public int CaseId { get; set; }
    ...

    [XmlArray("LeisureTimeActivities"), DefaultValue(null)]
    [XmlArrayItem("LeisureTimeActivity")]
    public List<int> LeisureTimeActivities { get; set; }
    public string LeisureTimeActivityOthers { get; set; }
    ...
    
    public string Observation { get; set; }
}
1

There are 1 best solutions below

1
On

Here is a working demo you could follow:

var mySerializer = new XmlSerializer(typeof(DetailAssessmentRequest));
//To read the file, create a xml string.
var xmlstring = System.IO.File.ReadAllText("XMLFile.xml");
//Parse to XDocument and remove the empty or null value
var document = XDocument.Parse(xmlstring);
document.Descendants()
        .Where(e => e.IsEmpty || String.IsNullOrWhiteSpace(e.Value))
        .Remove();
// Call the Deserialize method and cast to the object type.
var myObject = (DetailAssessmentRequest)mySerializer.Deserialize(document.CreateReader());