I’m trying to convert this xml file to C# object but it doesn’t work. I can’t to get text between Group tags. The classes structure let me to get childs inside Group tag, but when Group tag has just one text inside, I can’t select it.
I give the XML structure and my classes.
XML file:
<?xml version="1.0" encoding="utf-8"?>
<Main>
<Group>
<NV>BasicPars</NV>
<Property>
<NV>Name</NV>
<Value>wzorzec</Value>
</Property>
<Property>
<NV>UseFixedSizes</NV>
<Value>False</Value>
</Property>
</Group>
<Group>EventPars</Group>
<Group>Registers</Group>
</Main>
My classes:
[XmlRoot(ElementName="Property")]
public class Property {
[XmlElement(ElementName="NV")]
public string NV { get; set; }
[XmlElement(ElementName="Value")]
public string Value { get; set; }
}
[XmlRoot(ElementName="Group")]
public class Group {
[XmlElement(ElementName="NV")]
public string NV { get; set; }
[XmlElement(ElementName="Property")]
public List<Property> Property { get; set; }
}
[XmlRoot(ElementName="Main")]
public class Main {
[XmlElement(ElementName="Group")]
public List<Group> Group { get; set; }
}
>Solution :
First, you only need XmlRoot on the root object (that is, Main). Remove it from the others.
In order to capture the text inside an element, use [XmlText].
The fixed classes are:
public class Property {
[XmlElement(ElementName="NV")]
public string NV { get; set; }
[XmlElement(ElementName="Value")]
public string Value { get; set; }
}
public class Group {
[XmlElement(ElementName="NV")]
public string NV { get; set; }
[XmlElement(ElementName="Property")]
public List<Property> Property { get; set; }
[XmlText]
public string InnerText { get; set; }
}
[XmlRoot(ElementName="Main")]
public class Main {
[XmlElement(ElementName="Group")]
public List<Group> Group { get; set; }
}
Which deserializes correctly.