I am working on an application that parses XML document and serializes it. I am able to parse and convert to JSON but the issue.
What I want to achieve is to add an empty array structure in json if that element node is not there in XML. But from my code, the output is coming as element : null
.
What I have done so far -
My class:
[Serializable()]
[XmlRoot("CarCollection")]
public class CarCollection
{
[XmlArray("Cars")]
[XmlArrayItem("Car", typeof(Car))]
public Car[] Car { get; set; }
}
[Serializable()]
public class Car
{
[XmlElement("StockNumber")]
public string stockNumber { get; set; }
[XmlElement("Make")]
public string make { get; set; }
[XmlArray("Models")]
[XmlArrayItem("model", typeof(Model))]
public Model[] Model { get; set; }
}
[Serializable()]
public class Model
{
[XmlElement("modelName")]
public string modelName { get; set; }
[XmlElement("modelType")]
public string modelType { get; set; }
[XmlElement("price")]
public string price { get; set; }
[XmlElement("preOrderNeeded")]
public string preOrderNeeded { get; set; }
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Renault</Make>
<Models>
<model>
<modelName>Kwid</modelName>
<modelType>Basic</modelType>
<price>5 Lakhs</price>
<preOrderNeeded>No</preOrderNeeded>
</model>
<model>
<modelName>Kwid</modelName>
<modelType>Compact Model with all upgrades</modelType>
<price>7.25 Lakhs</price>
<preOrderNeeded>Yes</preOrderNeeded>
</model>
</Models>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
</Car>
</Cars>
</CarCollection>
My logic for serialization:
CarCollection cars = null;
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
using (StreamReader sr = new StreamReader(@"C:\Users\someNAme\Downloads\XML\modelXML.xml"))
{
cars = (CarCollection)serializer.Deserialize(sr);
string output = JsonConvert.SerializeObject(cars);
}
This is what I am getting:
{
"stockNumber": "1010",
"make": "Toyota",
"Model": null
}
I want to achieve:
{
"stockNumber": "1010",
"make": "Toyota",
"Model": []
}