I've been given an xml containing two elements that have the same namem, 'Log', but where each 'Log' element has different attribute names. E.g. the first 'Log' element has attribute name 'AttrA' and the second 'Log' element has 'AttrB'. I've tried using XmlArrayItem, but don't get it to read in the array. In the code below, the 'myObjectWithoutLog' object contains Elm, but not the Log data. Anybody know how I can get the two Log elements into the serialized object?
XML
<Elm DbLocation="C:\Data\Db\My.db">
<Log AttrA="C:\Data\Log\Log1.csv"/>
<Log AttrA="C:\Data\Log\Log2.csv"/>
</Elm>
C#
[XmlRoot(ElementName = "Elm", Namespace = "")]
public class myXmlObject
{
public myXmlObject()
{
}
[XmlAttribute("DbLocation", Namespace = "")]
public string DbLocation { get; set; }
[XmlArrayItem("Log", Namespace = "")]
public List<Log> logs { get; set; }
}
[XmlRoot(ElementName = "Log", Namespace = "")]
public class Log
{
[XmlAttribute("AttrA", Namespace = "")]
public string attrA { get; set; }
[XmlAttribute("AttrB", Namespace = "")]
public string attrB { get; set; }
}
public class RunIt
{
XmlSerializer serializer = new XmlSerializer(typeof(myXmlObject));
using (FileStream stream = new FileStream(myXmlFile, FileMode.Open))
{
myXmlObject myObjectWithoutLog = (myXmlObject)serializer.Deserialize(stream);
}
}
CodePudding user response:
Sorry there were a typo in the XML above, the correct is posted here below, the problem still remains the same though.
XML
<Elm DbLocation="C:\Data\Db\My.db">
<Log AttrA="C:\Data\Log\Log1.csv"/>
<Log AttrB="C:\Data\Log\Log2.csv"/>
</Elm>
CodePudding user response:
You're using wrong Xml attribute. You need to use XmlElement instead of XmlArrayItem.
[XmlRoot(ElementName = "Elm", Namespace = "")]
public class myXmlObject
{
public myXmlObject()
{
}
[XmlAttribute("DbLocation", Namespace = "")]
public string DbLocation { get; set; }
[XmlElement("Log", Namespace = "")]
public List<Log> logs { get; set; }
}
[XmlRoot(ElementName = "Log", Namespace = "")]
public class Log
{
[XmlAttribute("AttrA", Namespace = "")]
public string attrA { get; set; }
[XmlAttribute("AttrB", Namespace = "")]
public string attrB { get; set; }
}