Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading