1

I have an xml file with child nodes that I want to read. When I deserialize the object I won't get the value from the child nodes, its always 0.

Xmlfile example:

<?xml version="1.0" encoding="utf-8"?>
<Pieces Rapport="0" Employee="">
  <Piece Roll="1" Piece="1" Amount="1" Length="1.00" />
  <Piece Roll="1" Piece="1" Amount="1" Length="2.00" />
  <Piece Roll="1" Piece="1" Amount="1" Length="3.00" />
  <Piece Roll="1" Piece="1" Amount="1" Length="0" />
  <Piece Roll="1" Piece="1" Amount="1" Length="0" />
</Pieces>

I marked my classes with the [XmlElement] tag as stated here: How to deserialize xml to object

classes:

  [XmlRoot("Pieces")]
public class StukLijst
{
    [XmlElement("Rapport")]
    public string rapport { get; set; }
    [XmlElement("Employee")]
    public string employee { get; set; }
    [XmlElement("Piece")]
    public List<StukRow> stukLijst { get; set; }
}

 public class StukRow
{
    [XmlElement("Roll")]
    public int rol { get; set; }
    [XmlElement("Piece")]
    public int stuk { get; set; }
    [XmlElement("Amount")]
    public int banen { get; set; }
    [XmlElement("Length")]
    public double lengte { get; set; }
}

read the xml file:

private void LoadXml(string pickListNumber, string lineNumber)
    {
        string path = filePath + pickListNumber + "_" + lineNumber + ".xml";
        StreamReader xmlStream = new StreamReader(path);
        XmlSerializer serializer = new XmlSerializer(typeof(StukLijst));
        StukLijst result = (StukLijst)serializer.Deserialize(xmlStream);
    }

and the result is the following:

result

So why is Employee null while the childnodes are all 0? It seems like it can find the childs but doesn't get the data from them. Any solutions?

Proliges
  • 371
  • 4
  • 26
  • Arent you mixing elements and attributes? A new XML node is an element, but `Rapport` and `Employee` are not new XML nodes, but attributes of the existing `Pieces` node/element – Cleptus Mar 15 '21 at 08:53

1 Answers1

4

You've used [XmlElement] in each of your properties in StukRow, but the data isn't in XML elements - it's in XML attributes. Try this instead:

public class StukRow
{
    [XmlAttribute("Roll")]
    public int rol { get; set; }
    [XmlAttribute("Piece")]
    public int stuk { get; set; }
    [XmlAttribute("Amount")]
    public int banen { get; set; }
    [XmlAttribute("Length")]
    public double lengte { get; set; }
}

Likewise your rapport and employee properties in StukLijst should be decorated with [XmlAttribute] as the data is in stored in XML attributes, not child elements.

As a side-note, I'd strongly encourage you to start following .NET naming conventions for your properties, using PascalCased names (e.g. Rol, Stuk etc.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194