xmldartelementchildren

How to get children of xml element with dart?


I would like to have all children of an element.

I have tried following:

import 'package:xml/xml.dart';
import 'dart:async';
import 'dart:io';
import 'package:xml/xpath.dart';

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


final document = XmlDocument.parse(bookshelfXml);

void main() async {
  var lines = document.findAllElements('document')
      .first.findElements('line')
      .where((line) => line.getAttribute('id') == '1')
      .forEach((e) {print('aaaa $e');});

}

The expectation here that I'll have a list of data element which are children of the line with id=1

aaaa <data id="D1" value="20"/>
aaaa <data id="D2" value="40"/>

but I had:

aaaa <line id="1">
<data id="D1" value="20"/>
<data id="D2" value="40"/>
</line>

I would like to get all the children of an element (by element's id) in to a list. But for xml package in dart, I still not find how to get it.


Solution

  • This'll do it. No need for all that mechanical walking when you have XPath nearby...

    import 'package:xml/xml.dart';
    import 'package:xml/xpath.dart';
    
    void main(List<String> arguments) {
      final document = XmlDocument.parse(bookshelfXml);
      final nodes = document.xpath('/document/line[@id="1"]/*');
      for (final node in nodes) {
        print('aaaa $node');
      }
    }
    
    const bookshelfXml = '''
    <?xml version="1.0" encoding="utf-8"?>
    <document id="doc1">
    <line id="1">
    <data id="D1" value="20" />
    <data id="D2" value="40" />
    </line>
    <line id="2">
    <data id="D1" value="90" />
    <data id="D2" value="340" />
    </line>
    </document>''';
    

    which seems to print exactly what you want:

    aaaa <data id="D1" value="20"/>
    aaaa <data id="D2" value="40"/>