Search code examples
xmlnodeselementnodelist

Nodelist vs Node vs Element


If you had an XML file like this

<Users>
  <student>
    <firstname> Chris </firstname>
    <lastname> Smith </lastname>
    <address> 1313 Mockingbird Lane </address>
    <phone> 555-1313 </phone>
  </student>
  <student>
    <firstname> John </firstname>
    <lastname> Doe </lastname>
    <address> 1526 Bluebird Way </address>
    <phone> 555-8324 </phone>
  </student>
</Users>

Then would...

  1. Users be considered a Nodelist?
  2. Student be considered an Element or a Nodelist? The student tag contains more tags, but it is also the child of the tag Users. So would this be an Element or Nodelist?
  3. The value "John" be a Node?

If I am mistaken in one of these, can you please tell me how to find out the difference between a node, element, and nodelist?


Solution

  • You are mixing some loosely defined terminology, and it's important to separate general concepts from specific meanings in the context of XML.

    In XML an "element" is a <tag>...</tag> and that definition can be applied recursively to nested tags (elements can contain elements).

    Node and NodeList are general concepts. A Node is, roughly, a distinct object with some internal state. The name Node implies that the object can be or is a member of some collection, often but not always a list.

    A NodeList is just a linear list of nodes. There are other types of collection that can contain nodes, such as a Map or Graph or Tree.

    In your example:

    Users is an XML element. It is also conceptually a node in the XML tree. It contains student elements so it is also a collection, and since the elements are arranged linearly, it is also a node list.

    A student is an XML element, and conceptually it is also a node in the list of students.

    The firstname tag (and everything inside it) is also an XML element and a node in the XML tree of nodes.

    The value John is not an element as defined by XML. It is a text node contained in firstname.