Search code examples
c#xml

How to convert xml file to C# object?


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

  • public class Serializer
        {       
            public T Deserialize<T>(string input) where T : class
            {
                System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
    
                using (StringReader sr = new StringReader(input))
                {
                    return (T)ser.Deserialize(sr);
                }
            }
    
            public string Serialize<T>(T ObjectToSerialize)
            {
                XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());
    
                using (StringWriter textWriter = new StringWriter())
                {
                    xmlSerializer.Serialize(textWriter, ObjectToSerialize);
                    return textWriter.ToString();
                }
            }
        }