Sample code for 30+ languages & platforms
Dart

AddAttribute - Insert New Attribute in an XML Node

Demonstrates adding an name=value attribute to an XML element.

This example uses the XML sample file here: sample1.xml. The sample1.xml file contains this content:

Chilkat Dart Downloads

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  final xml = CkXml();

  try {
    xml.loadXmlFile('qa_data/xml/sample1.xml');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Navigate to the "books" element:
  try {
    xml.findChild2('books');
  } on ChilkatException {
    print('No books child found!');
    return;
  }

  final numChildren = xml.numChildren;

  var i = 0;
  while (i < numChildren) {

    // Navigate to the Nth book 
    xml.getChild2(i);

    // Display the book title:
    print(xml.getAttrValue('title'));

    // Add a new integer attribute:
    // Should never fail..
    xml.addAttributeInt('bookId', i);

    // Add a new unread="yes" attribute:
    xml.addAttribute('unread', 'yes');

    // Navigate back up to the parent:
    xml.getParent2();

    i++;
  }

  // Navigate back to the document root:
  xml.getRoot2();

  // Save the updated document:
  try {
    xml.saveXml('modified.xml');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  print(xml.getXml());
}