Dart
Dart
XML SearchForAttribute Method
See more XML Examples
Demonstrates the SearchForAttribute method.The input XML, available at http://www.chilkatsoft.com/data/fruitSearch.xml, is this:
<root>
<searchRoot>
<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>
</searchRoot>
<fruit color="red">strawberry</fruit>
<fruit color="orange">peach</fruit>
</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/fruitSearch.xml');
} on ChilkatException {
success = false;
}
if (!success) {
print(xml.lastErrorText);
return;
}
// Search the sub-tree rooted at "searchRoot";
var xSearchRoot = xml.findChild('searchRoot');
if (!xml.lastMethodSuccess) {
print('searchRoot not found, searching from root.');
xSearchRoot = xml.getRoot();
}
// Search for all "fruit" nodes having a color attribute
// where the name of the color ends in "e";
var xBeginAfter = xSearchRoot.getSelf();
var xFound = xSearchRoot.searchForAttribute(xBeginAfter, 'fruit', 'color', '*e');
while (xSearchRoot.lastMethodSuccess) {
print('${xFound.content}: ${xFound.getAttrValue('color')}');
xBeginAfter = xFound;
xFound = xSearchRoot.searchForAttribute(xBeginAfter, 'fruit', 'color', '*e');
}
// The correct output is:
// grape: purple
// blueberry: blue
print('--------------------------');
// ---------------------------------------------------------------------------------
// Now do the same, but instead use SearchForAttribute2
// which updates the internal reference of the caller instead
// of returning the found node.
xBeginAfter = xSearchRoot.getSelf();
final xSearch = xSearchRoot.getSelf();
success = true;
try {
xSearch.searchForAttribute2(xBeginAfter, 'fruit', 'color', '*e');
} on ChilkatException {
success = false;
}
while (success) {
print('${xSearch.content}: ${xSearch.getAttrValue('color')}');
// Copy the internal references so that the next search
// begins after the found node.
xBeginAfter.copyRef(xSearch);
xSearch.copyRef(xSearchRoot);
success = true;
try {
xSearch.searchForAttribute2(xBeginAfter, 'fruit', 'color', '*e');
} on ChilkatException {
success = false;
}
}
}