user3185563
user3185563

Reputation: 1484

Dart xml find element from attribute value

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);
      }
    }

Upvotes: 1

Views: 1255

Answers (2)

Lukas Renggli
Lukas Renggli

Reputation: 8947

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.

Upvotes: 2

Vysl Shn
Vysl Shn

Reputation: 99

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

Example Code Link

Upvotes: 0

Related Questions