So if I have 3 different files that contain extremely long and complex xml (which i've abbreviated here) but just the root element name is different (not really random but I'd rather not duplicate classes for the same xml):
File 1
<?xml version="1.0"?>
<somerootname1>
<car>
<make>honda</make>
<model>civic</model>
</car>
</somerootname1>
File 2
<?xml version="1.0"?>
<somerootname2>
<car>
<make>honda</make>
<model>civic</model>
</car>
</somerootname2>
File 3
<?xml version="1.0"?>
<somerootname3>
<car>
<make>honda</make>
<model>civic</model>
</car>
</somerootname3>
Because XmlRootAttribute has AllowMultiple=false
I can't create a single class to represent the previous xml.
Duplicate 'XmlRootAttribute' attribute
[XmlRoot(ElementName="somerootname1")]
[XmlRoot(ElementName="somerootname2")]
public class Root
{
public Automobile Car { get; set; }
}
public class Automobile
{
public string Make { get; set; }
public string Model { get; set; }
}
I thought I might be able to be sneaky and grab just the element I need and deserialize it:
var xDoc = XDocument.Parse("myfile.xml");
var xCar = xDoc.Root.Descendants()
.FirstOrDefault(d => d.Name.LocalName.Equals("car"))
var serializer = new XmlSerializer(typeof(Automobile))
using (var reader = xml.CreateReader())
{
result = (Automobile)serializer.Deserialize(reader);
}
However that results in an InvalidOperationException
:
There is an error in XML document (0, 0).
With an InnerException:
<car> was not expected.
It seems really hacky to either; rename the root element and then deserialize OR take the element and prefix the <?xml>
tag. Any other suggestions?