Java
Chilkat2 Java
XML SearchForTag Method
See more XML Examples
Demonstrates the SearchForTag and SearchForTag2 methods.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 Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Xml;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
Xml xml = new Xml();
// The sample input XML is available at http://www.chilkatsoft.com/data/fruitSearch.xml
try {
xml.loadXmlFile("qa_data/xml/fruitSearch.xml");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Search the sub-tree rooted at "searchRoot";
Xml xSearchRoot = xml.findChild("searchRoot");
// Search for all nodes having the tag "fruit";
Xml xBeginAfter = xSearchRoot.getSelf();
Xml xFound = xSearchRoot.searchForTag(xSearchRoot, "fruit");
while (xSearchRoot.getLastMethodSuccess()) {
System.out.println(xFound.getContent());
xBeginAfter.close();
xBeginAfter = xFound;
xFound = xSearchRoot.searchForTag(xBeginAfter, "fruit");
}
xBeginAfter.close();
System.out.println("--------------------------");
// ---------------------------------------------------------------------------------
// Now do the same, but instead use SearchForTag2
// which updates the internal reference of the caller instead
// of returning the found node.
xBeginAfter = xSearchRoot.getSelf();
Xml xSearch = xSearchRoot.getSelf();
try {
xSearch.searchForTag2(xBeginAfter, "fruit");
success = true;
} catch (ChilkatException e) {
success = false;
}
while (success) {
System.out.println(xSearch.getContent());
// Copy the internal references so that the next search
// begins after the found node.
xBeginAfter.copyRef(xSearch);
xSearch.copyRef(xSearchRoot);
xSearch.searchForTag2(xBeginAfter, "fruit");
}
xSearch.close();
xBeginAfter.close();
xSearchRoot.close();
}
}