Using Kml: Accessing KmlDocument

Friends

I have a KML data file.

I would like to use the kml crate to access its properties

I can find no examples in the documentatiuon for how to access the internal KmlDocument

    let file_name = "data/Job-322-polygons.kml"; //args[1].as_str();
    let kml_str = fs::read_to_string(file_name).expect("Cannot read file: {file_name}");
    let kml:Kml = kml_str.parse().unwrap();
    eprintln!("kml: {kml:?}");

The output string (which is big and full of IP) starts with:

kml: KmlDocument(KmlDocument { version: Unknown, attrs: {}, elements: [Document { attrs: {"id":

KmlDocument is documented KmlDocument in kml::types - Rust but I cannot get at it

What am I missing?

Based on the documentation:[1]

let Kml::KmlDocument(document) = kml else {
    panic!("{file_name}: Valid KML but not a document")
};
println!("{document:?}");

I.e. a Kml::KmlDocument is only one possible variant of the Kml type.


  1. I.e. I have no experience with this crate ↩ī¸Ž

Kml is an enum type, so you can use patterns in a match or if let expression to access its contents.

let kml: Kml = kml_str.parse().unwrap();
match kml {
    Kml::KmlDocument(doc) => {
        // `doc` has type `KmlDocument`
        let first_element = doc.elements[0];
        let first_element_id = first_element.attrs["id"];
        //. ..
    }
    Kml::Scale(scale) => {
        // ...
    }
    _ => {
        // ...
    }
}
2 Likes

ALmost!

	Kml::KmlDocument(doc) => {
            // `doc` has type `KmlDocument`
            let first_element = &doc.elements[0];
            let first_element_id = &doc.attrs["id"];
            //. ..
	}

Thank you, very helpful.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.