Search code examples
xml

Using similar tags for different objects in XML


I want to define several non-inherited object types. I want to know whether I can use similar tags for them in XML. Some objects do not have the common tags. For example, the tag "name" below.

<?xml version="1.0" encoding="UTF-8"?>
<stuff>
    <person>
        <name>
            John
        </name>
        <age>
            30
        </age>
    </person>
    <car>
        <name>
            BMW
        </name>
        <price>
            50000
        </price>
    </car>
    <book>
        <name>
            Harry Potter
        </name>
        <author>
            Rowling
        </author>
    </book>
    <city>
        <country>
            USA
        </country>
        <population>
            5000000
        </population>
    </city>
</stuff>

Do we encounter any problems? In case of no theoretical error, can it make a "misunderstanding" in a large XML? Can it be problematic when we try to convert this XML to formats like SQL, Excel, Access, MongoDB etc?


Solution

  • Using a same-named element (such as your name example) as a child of two different parent elements such as person and car is natural and fully supported by XML and its related standards:

    • DTD supports defining same-named elements with different parents
      <!DOCTYPE people_list [
        <!ELEMENT person (name, age)>
        <!ELEMENT car (name, price)>
        <!ELEMENT name (#PCDATA)>
        <!ELEMENT age (#PCDATA)>
        <!ELEMENT price (#PCDATA)>
      ]>
    
    • XSD supports it too: See Basic Concepts: The Purchase Order in the XSD primer.

    • XPath (and therefore XSLT) differentiates between /stuff/person/name versus /stuff/car/name.

    • Etcetera.

    Note that the content models of name could even be different for the name of a person vs the name of a car. Well-formed XML allows the content models to differ for same-named elements with the same parent even, but XML schemas (such as DTD and XSD) generally do not support the definition of such elements, so such XML would generally not be able to be considered valid.

    See also