dartpetitparser

How do I do a "getElementsByTagName" using the Dart Petitparser XML parser?


I may have overlooked it somewhere, but what is the nice way to get all elements of a specific name (similar to the old getElementsByTagName) via the Dart version of PetitParser?

I managed to load an XML file and successfully parse it using PetitParser, but now I want to go through all nodes with a specific name (eg. see below nodes with the "importantData").

The result.value.length also seems to be very high (16654) for the 665 "importantData" nodes from my test xml file which are in result.value.children[1].children

<xml>
  <toplevel>
    <importantData>
       <attribute1>Value</attribute1>
       <attribute2>Value</attribute2>
    </importantData>
    <importantData>
       <attribute1>Value</attribute1>
       <attribute2>Value</attribute2>
    </importantData>
    <importantData>
       <attribute1>Value</attribute1>
       <attribute2>Value</attribute2>
    </importantData>
    ...
  </toplevel>
</xml>

Solution

  • The XmlNode is an Iterable<XmlNode> over all its children.

    If root is the parsed root node of your XML tree you can write:

    for (var node in root) {
      if (node is XmlElement && node.name.local == 'importantData') {
        // do something with the node
      }
    }
    

    If you are more into functional programming, you can use the following expression returning an iterable over all elements in question:

    root.where((node) => node is XmlElement && node.name.local == 'importantData')