Home > Software design >  Dart xml find element from attribute value
Dart xml find element from attribute value

Time:07-25

Given the xml below, what is the most efficient way to access a line element with a specific id attribute value, e.g. line id="2"?

<?xml version="1.0" encoding="utf-8"?>
<document id="doc1">
  <line id="1">
    <data id="D1" value="20" />
eating
    <data id="D2" value="40" />
  </line>
  <line id="2">
    <data id="D1" value="90" />
drinking
    <data id="D2" value="340" />
  </line>
</document>

This is what I have at the moment. I don't know if there is a better way:

var lines = document.findAllElements('line');
    for (var line in lines) {
      if (line.getAttribute("id") == "2") {
        print(line);
      }
    }

CodePudding user response:

you can use xml2json package for converting. I made an example for you on the link that below

Example Code Link

CodePudding user response:

Your code looks fine. Slightly simpler would be to filter with Iterable.where:

var lines = document.findAllElements('line')
    .where((line) => line.getAttribute('id') == '2')
    .toList();

At the end (optionally), I am converting the Iterable to a List, to make sure the document is only traversed and filtered once.

  • Related