Search code examples
xmldartxpathattributes

How to get the attribute value from xpath in dart?


I try to get the attribute value from xpath with this:

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 nn=[];
final document = XmlDocument.parse(bookshelfXml);
void main (List<String> arguments) {
  final document = XmlDocument.parse(bookshelfXml);
  final nodes = document.xpath('/document/line[@id="1"]/*/@id');
 
  for (final node in nodes) {
    nn.add(node);
  }
  for (var i=0; i<nn.length; i++) {
    print('id${i+1} is ${nn[i]}');
  }
}

The expectation here is

id1 is D1
id2 is D2

but I got

id1 is id="D1"
id2 is id="D2"

I need the solution which help me extract attribute's value (D1, D2) only not the value with the attribute name (id="D1", id="D2").


Solution

  • As opted in my comment:

    you can use node.value like this:

    for (final node in nodes) {
        nn.add(node.value);
    }