Home > Back-end >  Deserialize XML element returning null value
Deserialize XML element returning null value

Time:06-11

I have some data in an XML file. I am trying to deserialize the XML to some classes I have created.

I have been able to deserialize all the attributes of the PointCode and CodeAttributes elements. However, I can't seem to get the TextListValue attribute of the textList element.

The textList element returns a null value. I am using c# and using System.Xml.Serialization

[XmlRoot("PointCode")]
public class PointCode
{
    [XmlAttribute("codeLinework")]
    public string codeLinework { get; set; }

    [XmlElement("CodeAttributes")]
    public List<CodeAttributes> codeAttributes { get; set; }
}

[XmlRoot("CodeAttributes")]
public class CodeAttributes
{
    [XmlAttribute("attributeName")]
    public string attributeName { get; set; }

    [XmlAttribute("attributeType")]
    public string attributeType { get; set; }

    [XmlAttribute("valueType")]
    public string valueType { get; set; }

    [XmlAttribute("valueRegion")]
    public string valueRegion { get; set; }

    [XmlElement("text")]
    public Text text { get; set; }

}

[XmlRoot("text")]
public class Text
{
    [XmlElement("textChoiceList")]
    public TextChoiceList textChoiceList { get; }
}

[XmlRoot("textChoiceList")]
public class TextChoiceList
{
    [XmlElement("textList")]
    public List<TextList> textList { get; set; }

}

[XmlRoot("textList")]
public class TextList
{
    [XmlAttribute("textListValue")]
    public string textListValue { get; set; }
}

Extract of the XML file I am deserializing.

<Code codeName="KERB" codeDesc="Kerbs" codeType="Point">
  <PointCode codeLinework="open line">
    <CodeAttributes attributeName="String" attributeType="Normal" valueType="Integer" valueRegion="None">
      <integer />
    </CodeAttributes>
    <CodeAttributes attributeName="Type" attributeType="Normal" valueType="Text" valueRegion="ChoiceList">
      <text>
        <textChoiceList>
          <textList textListValue="Square Kerb" />
          <textList textListValue="Roll Kerb" />
        </textChoiceList>
      </text>
    </CodeAttributes>

CodePudding user response:

The missing setter for textChoiceList property in the Text class that leads to the text was null as the only property in the class is unable to set value.

So adding the missing setter to the property will solve the issue.

[XmlRoot("text")]
public class Text
{
    [XmlElement("textChoiceList")]
    public TextChoiceList textChoiceList { get; set; }
}

Sample .NET Fiddle

  • Related