Dart
Dart
Traverse Direct Children via FirstChild / NextSibling, or LastChild / PreviousSibling
See more XML Examples
Demonstrates some ways to iterate over direct child nodes using the FirstChild / NextSibling and LastChild / PreviousSibling methods.The input XML, available at http://www.chilkatsoft.com/data/fruit.xml, is this:
<root>
<fruit color="red">apple</fruit>
<fruit color="green">pear</fruit>
<veg color="orange">carrot</veg>
<meat animal="cow">beef</meat>
<xyz>
<fruit color="blue">blueberry</fruit>
<veg color="green">broccoli</veg>
</xyz>
<fruit color="purple">grape</fruit>
<cheese color="yellow">cheddar</cheese>
</root>
Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
final xml = CkXml();
success = true;
try {
xml.loadXmlFile('qa_data/xml/fruit.xml');
} on ChilkatException {
success = false;
}
if (!success) {
print(xml.lastErrorText);
return;
}
// Iterate over the direct children by using FirstChild / NextSibling
var child = xml.firstChild();
var bContinue = xml.lastMethodSuccess;
while (bContinue) {
print('${child.tag} : ${child.content}');
final nextSibling = child.nextSibling();
bContinue = child.lastMethodSuccess;
child = nextSibling;
}
print('-----');
// Do the same, but with FirstChild2 / NextSibling2 to avoid
// creating so many XML object instances:
success = xml.firstChild2();
while (success) {
print('${xml.tag} : ${xml.content}');
success = xml.nextSibling2();
}
// Revert back up to the parent:
success = true;
try {
xml.getParent2();
} on ChilkatException {
success = false;
}
print('-----');
// Iterate in reverse order using LastChild / PreviousSibling
child = xml.lastChild();
bContinue = xml.lastMethodSuccess;
while (bContinue) {
print('${child.tag} : ${child.content}');
final prevSibling = child.previousSibling();
bContinue = child.lastMethodSuccess;
child = prevSibling;
}
print('-----');
// Do the same, but with LastChild2 / PreviousSibling2 to avoid
// creating so many XML object instances:
success = true;
try {
xml.lastChild2();
} on ChilkatException {
success = false;
}
while (success) {
print('${xml.tag} : ${xml.content}');
success = true;
try {
xml.previousSibling2();
} on ChilkatException {
success = false;
}
}
// Revert back up to the parent:
success = true;
try {
xml.getParent2();
} on ChilkatException {
success = false;
}
}