SteveJ71
SteveJ71

Reputation: 15

I am unable to deserialize the following XML file

I am trying to deserialize an XML file. The relevant part of the XML is below.

The XML File:

<?xml version="1.0" encoding="utf-8"?>
    <LandXML xmlns="http://www.landxml.org/schema/LandXML-1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.landxml.org/schema/LandXML-1.2 http://www.landxml.org/schema/LandXML-1.2/LandXML-1.2.xsd" version="1.2" date="2022-06-22" time="16:31:46.94" readOnly="false" language="English">
        <Units>
            <Metric linearUnit="meter" areaUnit="squareMeter" volumeUnit="cubicMeter" angularUnit="decimal dd.mm.ss" latLongAngularUnit="decimal degrees" temperatureUnit="celsius" pressureUnit="milliBars"/>
        </Units>
...

My Class:

using System;
using System.Xml.Serialization;

namespace MLS.SpatialViz.Hexagon
{
    [Serializable]
    [XmlRoot(ElementName = "LandXML", IsNullable = true)]

    public class LandXML
    {
        [XmlElement(ElementName = "Units")]
        public Units Units { get; set; }

    }

    public class Units
    {
        [XmlAttribute(AttributeName = "linearUnit")]
        public string LinearUnit { get; set; }

    }
}

I am trying to write "meter" to the console. It runs but no value is written.

public static void DeserealizeXML()
{
    string FileName = @"D:\Temp\824ABF00.xml";
    
    XmlSerializer serializer = new XmlSerializer(typeof(Hexagon.LandXML));

    Hexagon.LandXML landXML;

    using (XmlTextReader xmlReader = new XmlTextReader(FileName))
    {
        xmlReader.Namespaces = false;
        xmlReader.WhitespaceHandling = WhitespaceHandling.None;

        landXML = (Hexagon.LandXML)serializer.Deserialize(xmlReader);
    }

    Console.WriteLine($"LinearUnit: {landXML.Units.LinearUnit}");
    Console.ReadKey();
}

I don't get the answer I am hoping for. It runs without error but does not print "meter".

Upvotes: 0

Views: 116

Answers (1)

rene
rene

Reputation: 42443

You are missing a class for Metric. Each XmlElement needs a corresponding class for the serialization to work. Units has a Metric element. You missed that one.

Using these classes:

[Serializable]
[XmlRoot(ElementName = "LandXML")]
public class LandXML
{
  [XmlElement(ElementName = "Units")]
  public Units Units { get; set; }
}
public class Units
{
  [XmlElement(ElementName = "Metric")]
  public Metric Metric { get; set; }
}
public class Metric
{
  [XmlAttribute(AttributeName = "linearUnit" )]
  public string LinearUnit { get; set; }
}

and then making this change:

Console.WriteLine($"LinearUnit: {landXML.Units.Metric.LinearUnit}");

will output

LinearUnit: meter

Do know there are online tools to assist you in generating Data Transfer Objects from Xml, for example https://xmltocsharp.azurewebsites.net/ can do that or your favorite IDE might offer an extension to do the same.

Upvotes: 0

Related Questions