Dart语言和XML包:读取节点(文本内容)

时间:2014-11-12 13:46:31

标签: xml dart dart-async

我有一个XML文件,结构如下:

<?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>

我只在一个XML文件中有很多行节点,我无法改变这种结构。

因此,使用XML包,我应该如何处理才能从特定节点获取文本内容?

例如,我想从名为&#34; name&#34;的节点获取文本。来自第二行。

修改

到目前为止:

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 个答案:

答案 0 :(得分:0)

您可能不需要Completer

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
}

我还没有真正尝试过此代码,但根据软件包的README.md,它应该像这样工作:

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