Sample code for 30+ languages & platforms
React Native

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 React Native Downloads

React Native
import { Xml } from '@chilkat/react-native'

function chilkatExample() {
  let success = false;

  const xml = new Xml();

  success = true;
  try {
    xml.loadXmlFile('qa_data/xml/fruit.xml');
  } catch {
    success = false;
  }
  if (!success) {
    console.log(xml.lastErrorText);
    return;
  }

  // Iterate over the direct children by using FirstChild / NextSibling
  let child = xml.firstChild();
  let bContinue = xml.lastMethodSuccess;
  while (bContinue) {
    console.log(`${child.tag} : ${child.content}`);
    const nextSibling = child.nextSibling();
    bContinue = child.lastMethodSuccess;

    child = nextSibling;
  }

  console.log('-----');

  // Do the same, but with FirstChild2 / NextSibling2 to avoid
  // creating so many XML object instances:
  success = xml.firstChild2();
  while (success) {
    console.log(`${xml.tag} : ${xml.content}`);
    success = xml.nextSibling2();
  }

  // Revert back up to the parent:
  success = true;
  try {
    xml.getParent2();
  } catch {
    success = false;
  }

  console.log('-----');

  // Iterate in reverse order using LastChild / PreviousSibling
  child = xml.lastChild();
  bContinue = xml.lastMethodSuccess;
  while (bContinue) {
    console.log(`${child.tag} : ${child.content}`);
    const prevSibling = child.previousSibling();
    bContinue = child.lastMethodSuccess;

    child = prevSibling;
  }

  console.log('-----');

  // Do the same, but with LastChild2 / PreviousSibling2 to avoid
  // creating so many XML object instances:
  success = true;
  try {
    xml.lastChild2();
  } catch {
    success = false;
  }
  while (success) {
    console.log(`${xml.tag} : ${xml.content}`);
    success = true;
    try {
      xml.previousSibling2();
    } catch {
      success = false;
    }
  }

  // Revert back up to the parent:
  success = true;
  try {
    xml.getParent2();
  } catch {
    success = false;
  }
}