dart, add XmlElement

dart, flutter で XmlElementを追加する方法です。

import 'package:flutter/material.dart';
import 'package:xml/xml.dart' as xml;
import 'dart:async';
import 'dart:io';
import 'dart:core';

var bookshelfXml = '''<?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>
    </bookshelf>''';
var document = xml.parse(bookshelfXml);

var element_book = xml.XmlElement(xml.XmlName('book'));
var element_title = xml.xmlElement(xml.XmlName('title'))..attributes.add(xml.XmlAttribute(xml.XmlName('lang'), 'english'))..children.add(xml.XmlText('My book'));
var element_price = xml.XmlElement(xml.XmlName('price'))..children.add(xml.XmlText('19.95'));
element_book..children.add(element_title);
element_book..children.add(element_price);
document.rootElement.children.add(element_book);

この方法でbook要素に title が My book, price が 19.95 の book が追加されます。

<?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>
      <book>
        <title lang="english">My book</title>
        <price>19.95</price>
      </book>
    </bookshelf>

children.add に別のXmlDocumentのXmlNode, XmlElement などを配置すると例外が発生します。xml.XmlElement(xml.XmlName(“book”)) 等で生成または、xml.XmlElement.copy() を使用する必要があります。