带有外部文件的dart xml

时间:2016-08-08 07:56:55

标签: xml dart

我已经能够遵循dart-xml的所有示例,但这仅适用于变量中包含xml的dart文件。如何解析和创建外部xml文件?

如果我尝试直接导入xml文件,dart通常会卡在xml文件的第一个字符'<'。

如何从dart-xml https://github.com/renggli/dart-xml编写给定的示例?我可以使用

将它打印到shell
print(bookshelfXml.toString());

但是如何保存||将它管道到外部文件?我试过用dart:io有点但目前没有取得任何成功。

2 个答案:

答案 0 :(得分:1)

这应该做你想要的:

import 'dart:io';

...

var file = new File('path/to/file.xml');
file.writeAsString(bookshelfXml.toString());

另见:

答案 1 :(得分:1)

感谢renggli @ github,zoeichi for dart:io help。

使用外部文件dart-xml repo执行示例尝试;

import 'dart:io';
import 'package:xml/xml.dart' as xml;

void main (){

//create file bookshelf.xml seperately using example on github.
// <?xml version="1.0"?>
//     <bookshelf>
//       <book>
//         <title lang="english">Growing a Language</title>
//         <price>29.99</price>
//       </book>
//       <book>
//         <title lang="english">Learning XML</title>
//         <price>39.95</price>
//       </book>
//       <price>132.00</price>
//     </bookshelf>

//parse external file
var book = xml.parse(new File('bookshelf.xml').readAsStringSync());
print(book.toString());
print('---');

//finding elements
var titles = book.findAllElements('title');
titles
    .map((node) => node.text)
    .forEach(print);

//finding elements, convert strings to compute sum
var total =  book.findAllElements('book')
    .map((node) => double.parse(node.findElements('price').single.text))
    .reduce((a, b) => a + b);
print(total);   
print('---');

//build external file using example
var builder = new xml.XmlBuilder();
builder.processing('xml', 'version="1.0"');
builder.element('bookshelf', nest: () {
  builder.element('book', nest: () {
    builder.element('title', nest: () {
      builder.attribute('lang', 'english');
      builder.text('Growing a Language');
    });
    builder.element('price', nest: 29.99);
  });
  builder.element('book', nest: () {
    builder.element('title', nest: () {
      builder.attribute('lang', 'english');
      builder.text('Learning XML');
    });
    builder.element('price', nest: 39.95);
  });
  builder.element('price', nest: 132.00);
});
var bookshelfXml = builder.build();

//create and write eternal file name and contents 
var buildXml = new File('bookshelfDartCreated.xml');
buildXml.writeAsString(bookshelfXml.toString());

//check newly created file
new File('bookshelfDartCreated.xml').readAsString().then((String contents) {
  print(contents);
  });
}