0

I have an XML file with the following structure:

<?xml version='1.0' encoding='UTF8'?>
<root>
    <row filter="FILTER STRING"> // THIS IS THE FIRST "ROW"
        <id>100</id>
        <name>Some nome here</name>
        <text>TEXT CONTENT HERE</text>
    </row>
    <row filter="FILTER STRING"> // THIS IS THE SECOND "ROW"
        <id>101</id>
        <name>Some nome here</name>
        <text>TEXT CONTENT HERE</text>
    </row>
</root>

I'll have lots of rows nodes in just one XML file and I cannot change this structure.

So, with XML package, how should I proceed in order to be able to get the text content from specific nodes?

For example, I would like to get the text from the node called "name" from the SECOND ROW.

EDIT:

So far:

void main() {
    _readFile("test_UTF8.xml").then((xmlContent) {
        var parsedXml = parse(xmlContent);
            parsedXml.findAllElements("row").forEach((row) {
                // EACH "ROW" NODE WILL BE ITERATED HERE.
                // READ "ROW" CHILDREN NODES HERE.
                // FOR EXAMPLE: GET "NAME"'S TEXT CONTENT.
            });
    });
}

Future _readFile(String filename) {
    var completer = new Completer();
    new File(filename).readAsString().then((String xmlContent) {
        completer.complete(xmlContent);
    });
    return completer.future;
}
1
  • @GünterZöchbauer, I edited the question with what I have now. I've tried "findElements", but it returns a List of XmlElements, and I want to be precise (something like getElementById). Commented Nov 12, 2014 at 14:24

1 Answer 1

1

You probably don't need a Completer here

Future _readFile(String filename) {
  // a return here achieves the same in most cases
  return new File(filename).readAsString();
  // because this makes this method so short it doen't make much sense to 
  // even create a method for this
}

I haven't actually tried this code but according to the README.md of the package it should work like this:

void main() {
  new File("test_UTF8.xml").readAsString()
  .then((xmlContent) {
    var parsedXml = parse(xmlContent);
    return parsedXml.findElements("root")
        .first.findElements("row").toList()[1]
            .findElements('name').first.text; // <= modified
  })
  .then((text) {
    print(text);
  }); 
}
Sign up to request clarification or add additional context in comments.

5 Comments

It didn't work. I find that documentation lacking of simple examples, like this one in my question. ERROR: Unhandled exception: Uncaught Error: Class 'MappedIterable' has no instance getter 'text'.
Unhandled exception: Uncaught Error: Bad state: No element
Thanks! I'll wait for it.
I just copied the code and run it: Some nome here. (It took a while because pub upgrade took so long).
My bad. I didn't change the source to test and look for "name". It is working fine. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.