NiVO / BY TECHNOGISGermany · Indonesia
Inventory XML tutorial

KML Namespace URIs: Find Placemarks Without Depending on a Prefix

Compare default and prefixed KML element names, select the exact namespace URI, and preserve ordinary id attributes in a small offline inventory example.

KML Namespace URIs: Find Placemarks Without Depending on a Prefix

Investigate the selector before reporting missing features

A KML handoff may look readable in a text editor while an inventory script returns no placemarks. Before treating that result as evidence that mapped features disappeared, inspect how the script identifies XML elements. One document may place its elements in a default namespace, while another uses an explicit prefix. A selector that depends on the literal spelling of the prefix can fail even when both documents identify the same KML vocabulary. The receiving script needs to distinguish textual spelling from element identity.

This tutorial compares two small constructed XML documents and extracts only placemark identifiers and direct name text. It does not open a customer file, convert geometry, inspect an actual NiVO export, or establish that a KML document is valid for every application. The example isolates namespace matching so that a failed query can be explained precisely. The product photograph is separate catalogue context. No feature count from the teaching documents should be presented as a surveyed asset count or evidence that a real delivery is complete.

Match the namespace URI together with the local name

The W3C Namespaces in XML recommendation defines an expanded name using a namespace name and a local name. A prefix is bound to the namespace URI within its scope. Thus, an element written as p:Placemark can identify the same expanded name as an unprefixed Placemark under the appropriate default namespace. The Google KML reference uses http://www.opengis.net/kml/2.2 for its KML namespace. Preserve that exact identifier when selecting the elements in this example instead of guessing a prefix from a sample file.

Namespace identifiers are compared as strings. Do not automatically replace http with https, remove a trailing slash, or change letter case because the identifier resembles a web address. Those edits can produce a different namespace name. Likewise, do not discard every namespace and match only the word Placemark. A foreign vocabulary can use the same local name, and an unqualified element is not automatically a KML element. The useful comparison is the declared namespace identifier plus the local name, with both parts retained.

NiVO VTOL V7 with a white fuselage, lift rotors, and yellow wing tips
NiVO VTOL V7 with a white fuselage, lift rotors, and yellow wing tips.Source: NiVO / TechnoGIS catalogue materials supplied by the site owner · Catalogue photo
Product context only; this photograph does not depict the constructed examples in this article.

Compare default and prefixed documents with one reader

Python ElementTree represents parsed namespaced tags using braces around the URI followed by the local name. The function below uses that representation for its root check and its placemark and name selectors. It accepts only small trusted strings in this teaching profile. It returns the ordinary id attribute and the text from a direct KML name child, retaining None when the attribute or text is absent. More than one direct KML name is rejected as ambiguous for this narrow reader, rather than choosing an arbitrary one.

Run the example locally. Both strings bind their elements to the same KML URI, but one uses the default namespace and the other uses the prefix p. Each should return the same identifier P1 and name Marker A. No network request, file write, geometry transformation, or XML schema validation occurs. The length bound is a local demonstration limit, not a KML format limit. This is a trusted-literal parsing exercise; processing arbitrary external XML requires a parser and resource policy appropriate to that separate task.

import xml.etree.ElementTree as ET

KML = "http://www.opengis.net/kml/2.2"
def kml_inventory(xml_text):
    if type(xml_text) is not str or len(xml_text) > 8192:
        raise ValueError("Expected a small trusted XML teaching string")
    tag = lambda local: "{" + KML + "}" + local
    root = ET.fromstring(xml_text)
    if root.tag != tag("kml"):
        raise ValueError("Expected the exact KML namespace on the root")
    rows = []
    for placemark in root.findall(".//" + tag("Placemark")):
        names = placemark.findall(tag("name"))
        if len(names) > 1:
            raise ValueError("Ambiguous direct KML name children")
        rows.append({"id": placemark.get("id"),
                     "name": names[0].text if names else None})
    return rows

# Constructed namespace examples, not project inventory files.
default = '<kml xmlns="' + KML + '"><Placemark id="P1"><name>Marker A</name></Placemark></kml>'
prefixed = '<p:kml xmlns:p="' + KML + '"><p:Placemark id="P1"><p:name>Marker A</p:name></p:Placemark></p:kml>'
print(kml_inventory(default))
print(kml_inventory(prefixed))

Keep attribute identity separate from the default namespace

A default XML namespace applies to unprefixed element names in its scope, but it does not directly place ordinary unprefixed attributes in that namespace. That is why the example reads placemark.get with the plain attribute name id. Looking for a namespace-qualified id instead would ask for a different attribute. Conversely, a foreign prefixed attribute whose local name is id does not become the ordinary KML object identifier just because its visible suffix looks familiar. Preserve the complete attribute identity during inspection.

The function intentionally retains missing identifiers as None and preserves direct name text without trimming or substituting a convenient display value. It does not prove that identifiers are unique, that names are populated, or that a placemark contains valid geometry. Those are separate checks. If an export includes both ordinary and foreign attributes, inspect the attribute dictionary before deciding which one carries the intended association. Avoid a broad rule that strips namespace information from every key, because it can collapse distinct attributes into one misleading identifier.

Test namespace changes as well as prefix changes

A useful test set contains more than the two successful examples. Rename the prefix while keeping its URI unchanged and confirm that the same record is found. Then bind a similarly named element to a different URI and confirm that it is not counted as a KML placemark. A nested declaration can change the namespace in a smaller scope, so inspecting only the first namespace declaration is insufficient. The parser expanded name at each element is the evidence that the selector should follow.

Also test a genuine KML placemark that contains a foreign name element beside its direct KML name. The reader should use the KML name and leave the foreign element outside this result. If a subtree clears the default namespace with an empty declaration, its unprefixed elements no longer inherit the earlier KML namespace. These examples explain why a local-name-only search can appear helpful while quietly accepting elements outside the intended vocabulary. Keep the failing input alongside the diagnostic rather than rewriting declarations to force a match.

Deliver the selector and its limits with the inventory

For a real handoff investigation, retain the received document identity, parser version, exact namespace URI, selection path, identifier rule, and the expected small comparison set. Report whether the problem was an inappropriate prefix-dependent selector or a genuinely different namespace declaration. A successful namespace match is not a complete KML acceptance result. Continue the independent checks for geometry, coordinate meaning, referenced resources, object identity, and receiving-application behavior through the project workflow. The diagnostic should resolve the specific selection question without replacing those other checks.

In a NiVO-related inventory exchange, this approach can make a missing-record report easier to audit. Another reviewer can repeat the same URI-aware selector on the unchanged source and understand why a renamed prefix should not change its membership. Preserve the original XML rather than normalizing it merely to satisfy one brittle script. Deliver the result with its narrow scope: these are the identifiers and direct names found under the stated namespace rule, rather than a claim about the completeness, accuracy, or operational status of mapped assets.

When two tools still disagree, compare the exact parsed expanded names and their selection paths before comparing totals. One tool may search only direct children while another searches descendants, or one may follow additional linked resources outside the supplied document. The tutorial searches descendant KML placemarks within its parsed tree and reads only direct KML name children. Recording those choices prevents a namespace fix from being mistaken for evidence that every difference between the tools has been explained.

Technical references

  1. W3C Namespaces in XML: expanded names, URI comparison and default namespaces ↗
  2. Python ElementTree: parsing XML with namespaces ↗
  3. Google KML reference: the kml namespace declaration ↗
← All articles

Related articles

All articles ↗
LET’S TAKE FLIGHT

Your next mission
starts with a conversation.

Talk to our team