Search code examples
c#xmlkml

Unable to deserialize the kml


I have the following Kml:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <name>Trains</name>
    <description/>
      <name>Red Train</name>
  </Document>
</kml>

and the following code to deserialize it

private void KmlToObject()
{
    var path = @"C:\Users\Downloads\test.kml";
    var serializer = new XmlSerializer(typeof(Kml));
    using var reader = new StringReader(path);
    var obj = serializer.Deserialize(reader) as Kml;
}

[XmlRoot(ElementName = "kml")]
public class Kml
{
    [XmlElement(ElementName = "Document")]
    public object Document { get; set; }

    [XmlAttribute(AttributeName = "xmlns")]
    public string Xmlns { get; set; }
}

And I get the following error:

There is an error in XML document (1, 1).

What am I doing wrong?


Solution

  • StringReader is not the way to read the file.

    Initializes a new instance of the StringReader class that reads from the specified string.

    Instead, you should look for StreamReader with the ReadToEnd method. Reference: How to: Read text from a file

    var path = @"C:\Users\Downloads\test.kml";
    var serializer = new XmlSerializer(typeof(Kml));
    
    using (StreamReader sr = new StreamReader(path))
    {
        var obj = serializer.Deserialize(sr.ReadToEnd()) as Kml;
    }
    

    And provide the Namespace to XmlRoot attribute.

    [XmlRoot(ElementName = "kml", Namespace = "http://www.opengis.net/kml/2.2")]
    public class Kml
    {
        ...
    }