How to update XML Documents Using Java DOM Parser

HOME

package XML.DOM;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

public class DOM_ModifyXMLDemo {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilderFactory and DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            // Step 3: Update the XML content
            NodeList nodeList = document.getElementsByTagName("employee");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element employee = (Element) nodeList.item(i);
                String id = employee.getAttribute("id");

                if ("1".equals(id)) {
                    Element position = (Element) employee.getElementsByTagName("position").item(0);
                    position.setTextContent("Consultant");
                }
            }

            //Traverse the nodes to normalize spaces in text nodes
            Node rootNode = document.getDocumentElement();
            normalizeSpace(rootNode);

            //Write changes back to the XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            //Writing updated content into the file
            DOMSource domSource = new DOMSource(document);

            StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/UpdatedXML.xml"));
            transformer.transform(domSource, fileResult);

            // Print updated XML to console
            StreamResult consoleResult = new StreamResult(System.out);
            transformer.transform(domSource, consoleResult);

            System.out.println("\n XML file updated successfully!");

        } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

    private static void normalizeSpace(Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            String trimmedText = node.getTextContent().trim().replaceAll("\\s+", " ");
            node.setTextContent(trimmedText);
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            normalizeSpace(children.item(i));
        }
    }
}

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));
 document.getDocumentElement().normalize();
  NodeList nodeList = document.getElementsByTagName("employee");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Element employee = (Element) nodeList.item(i);
                String id = employee.getAttribute("id");

                if ("1".equals(id)) {
                    Element position = (Element) employee.getElementsByTagName("position").item(0);
                    position.setTextContent("Consultant");
                }
            }
private static void normalizeSpace(Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            String trimmedText = node.getTextContent().trim().replaceAll("\\s+", " ");
            node.setTextContent(trimmedText);
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            normalizeSpace(children.item(i));
        }
    }

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();

transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Pretty print the XML
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

DOMSource domSource = new DOMSource(document);

 // Write XML to file
 StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/UpdatedXML.xml"));
transformer.transform(domSource, fileResult);

StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(domSource, consoleResult);
try {
 } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

package XML.DOM;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

import static org.apache.commons.lang3.StringUtils.normalizeSpace;

public class DOM_ModifyXMLAddElementsDemo {

    public static void main(String[] args) {

        try {

            //Create a DocumentBuilderFactory and DocumentBuilder
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            //Locate the root element
            Element rootElement = document.getDocumentElement();

            // Create a new employee element
            Element employee = document.createElement("employee");
            employee.setAttribute("id", "4");

            // Create name element
            Element name = document.createElement("name");
            name.appendChild(document.createTextNode("Milly Mathew"));
            employee.appendChild(name);

            // Create position element
            Element position = document.createElement("position");
            position.appendChild(document.createTextNode("Architect"));
            employee.appendChild(position);

            //Append the new employee node to the root element
            rootElement.appendChild(employee);

            //Traverse the nodes to normalize spaces in text nodes
            Node rootNode = document.getDocumentElement();
            normalizeSpace(rootNode);

            //Write changes back to the XML file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            //Writing updated content into the file
            DOMSource domSource = new DOMSource(document);

            StreamResult fileResult = new StreamResult(new File("src/test/resources/Payloads/UpdatedXML1.xml"));
            transformer.transform(domSource, fileResult);

            // Print updated XML to console
            StreamResult consoleResult = new StreamResult(System.out);
            transformer.transform(domSource, consoleResult);

            System.out.println("\n XML file updated successfully!");

        } catch (ParserConfigurationException | TransformerException | IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }
    }

    private static void normalizeSpace(Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            String trimmedText = node.getTextContent().trim().replaceAll("\\s+", " ");
            node.setTextContent(trimmedText);
        }
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            normalizeSpace(children.item(i));
        }
    }

}

Element rootElement = document.getDocumentElement();
 // Create a new employee element
 Element employee = document.createElement("employee");
employee.setAttribute("id", "4");

// Create name element
Element name = document.createElement("name");
name.appendChild(document.createTextNode("Milly Mathew"));
employee.appendChild(name);

// Create position element
Element position = document.createElement("position");
position.appendChild(document.createTextNode("Architect"));
employee.appendChild(position);

//Append the new employee node to the root element
rootElement.appendChild(employee);

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Highlighting Elements in Selenium Java

HOME

package Web;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.time.Duration;

public class HighlightText_Example {

    public static void main(String args[]) {

        ChromeOptions chromeOptions = new ChromeOptions();
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.manage().window().maximize();

        try {
            driver.get("https://www.selenium.dev/");

            // identify the element
            WebElement element = driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[7]/div/a"));

            // Optionally, we wait to observe the element before changing the color
            Thread.sleep(1000);

            // Set the background color to yellow and the border to red
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("arguments[0].style.backgroundColor = 'yellow'; arguments[0].style.border = '3px solid red';", element);

            // Optionally, we can wait to observe the highlight effect
            Thread.sleep(2000);
            System.out.println("Text is highlighted");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            // Closing browser
            driver.quit();
        }
    }
}

ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.xpath("//*[@id='main_navbar']/ul/li[7]/div/a"));
  // Set the background color to yellow and the border to red
 JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.backgroundColor = 'yellow'; arguments[0].style.border = '3px solid red';", element);
 Thread.sleep(2000);
// Close the browser
driver.quit();

Retrieve Font Properties with Selenium in Java

HOME

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.IOException;
import java.time.Duration;

public class Font_Example {

    public static void main(String args[]) throws IOException {

        ChromeOptions chromeOptions = new ChromeOptions();
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        driver.manage().window().maximize();

        try {
            // Navigate to Url
            driver.get("https://www.selenium.dev/");

            WebElement element = driver.findElement(By.xpath("//*[@class='selenium-button-container']/a"));

            // Retrieve the font color
            String fontFamily  = element.getCssValue("font-family");
            System.out.println("fontFamily  : " + fontFamily );

            // Retrieve the font size
            String fontSize = element.getCssValue("font-size");
            System.out.println("fontSize : " + fontSize);

            // Retrieve the font weight
            String fontWeight = element.getCssValue("font-weight");
            System.out.println("fontWeight : " + fontWeight);

            // Retrieve the font style
            String fontStyle  = element.getCssValue("font-style");
            System.out.println("fontStyle : " + fontStyle);

            // Retrieve the font variation
            String fontVariant  = element.getCssValue("font-variant");
            System.out.println("fontVariant : " + fontVariant);

            // Retrieve the line height
            String lineHeight  = element.getCssValue("line-height");
            System.out.println("lineHeight : " + lineHeight);

            // Retrieve the letter spacing
            String letterSpacing  = element.getCssValue("letter-spacing");
            System.out.println("letterSpacing : " + letterSpacing);

            // Retrieve the text transform
            String textTransform  = element.getCssValue("text-transform");
            System.out.println("textTransform : " + textTransform);

            // Retrieve the text decoration
            String textDecoration  = element.getCssValue("text-decoration");
            System.out.println("textDecoration : " + textDecoration);

            System.out.println("####################### Verify the font properties #########################");

            // Verify the font family
            if (fontFamily.contains("Arial")) {
                System.out.println("fontFamily is as expected.");
            } else {
                System.out.println("fontFamily is not as expected. Found: " + fontFamily);
            }

            // Verify the font size
            if (fontSize.equals("16px")) {
                System.out.println("fontSize is as expected.");
            } else {
                System.out.println("fontSize is not as expected. Found: " + fontSize);
            }

            // Verify the font weight
            if (fontWeight.equals("500")) {
                System.out.println("fontWeight is as expected.");
            } else {
                System.out.println("fontWeight is not as expected. Found: " + fontWeight);
            }

            // Verify the font style
            if (fontStyle.equals("italic")) {
                System.out.println("fontStyle is as expected.");
            } else {
                System.out.println("fontStyle is not as expected. Found: " + fontStyle);
            }

            // Verify the font variant
            if (fontVariant.equals("small-caps")) {
                System.out.println("fontVariant is as expected.");
            } else {
                System.out.println("fontVariant is not as expected. Found: " + fontVariant);
            }

            // Verify the line height
            if (lineHeight.equals("24px")) {
                System.out.println("lineHeight is as expected.");
            } else {
                System.out.println("lineHeight is not as expected. Found: " + lineHeight);
            }

            // Verify the letter Spacing
            if (letterSpacing.equals("normal")) {
                System.out.println("letterSpacing is as expected.");
            } else {
                System.out.println("letterSpacing is not as expected. Found: " + letterSpacing);
            }

            // Verify the text Transform
            if (textTransform.equals("lowercase")) {
                System.out.println("textTransform is as expected.");
            } else {
                System.out.println("textTransform is not as expected. Found: " + textTransform);
            }

            // Verify the text Decoration
            if (textDecoration.equals("underline")) {
                System.out.println("textDecoration is as expected.");
            } else {
                System.out.println("textDecoration is not as expected. Found: " + textDecoration);
            }

        } finally {
            // Close the browser
            driver.quit();
        }
    }
}

ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
driver.manage().window().maximize();
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.xpath("//*[@class='selenium-button-container']/a"));
  1. text-transform – Modifies the capitalization of text. (e.g. uppercase, lowercase, capitalize)
// Retrieve the font color
String fontFamily  = element.getCssValue("font-family");
System.out.println("fontFamily  : " + fontFamily );

// Retrieve the font size
String fontSize = element.getCssValue("font-size");
System.out.println("fontSize : " + fontSize);

// Retrieve the font weight
String fontWeight = element.getCssValue("font-weight");
System.out.println("fontWeight : " + fontWeight);

// Retrieve the font style
String fontStyle  = element.getCssValue("font-style");
System.out.println("fontStyle : " + fontStyle);

// Retrieve the font variation
String fontVariant  = element.getCssValue("font-variant");
System.out.println("fontVariant : " + fontVariant);

// Retrieve the line height
String lineHeight  = element.getCssValue("line-height");
System.out.println("lineHeight : " + lineHeight);

// Retrieve the letter spacing
String letterSpacing  = element.getCssValue("letter-spacing");
System.out.println("letterSpacing : " + letterSpacing);

// Retrieve the text transform
String textTransform  = element.getCssValue("text-transform");
System.out.println("textTransform : " + textTransform);

// Retrieve the text decoration
String textDecoration  = element.getCssValue("text-decoration");
System.out.println("textDecoration : " + textDecoration);
// Verify the font family
if (fontFamily.contains("Arial")) {
    System.out.println("fontFamily is as expected.");
} else {
    System.out.println("fontFamily is not as expected. Found: " + fontFamily);
}

// Verify the font size
if (fontSize.equals("16px")) {
    System.out.println("fontSize is as expected.");
} else {
    System.out.println("fontSize is not as expected. Found: " + fontSize);
}

// Verify the font weight
if (fontWeight.equals("500")) {
    System.out.println("fontWeight is as expected.");
} else {
    System.out.println("fontWeight is not as expected. Found: " + fontWeight);
}

// Verify the font style
if (fontStyle.equals("italic")) {
    System.out.println("fontStyle is as expected.");
} else {
    System.out.println("fontStyle is not as expected. Found: " + fontStyle);
}

// Verify the font variant
if (fontVariant.equals("small-caps")) {
    System.out.println("fontVariant is as expected.");
} else {
    System.out.println("fontVariant is not as expected. Found: " + fontVariant);
}

// Verify the line height
if (lineHeight.equals("24px")) {
    System.out.println("lineHeight is as expected.");
} else {
    System.out.println("lineHeight is not as expected. Found: " + lineHeight);
}

// Verify the letter Spacing
if (letterSpacing.equals("normal")) {
    System.out.println("letterSpacing is as expected.");
} else {
    System.out.println("letterSpacing is not as expected. Found: " + letterSpacing);
}

// Verify the text Transform
if (textTransform.equals("lowercase")) {
    System.out.println("textTransform is as expected.");
} else {
    System.out.println("textTransform is not as expected. Found: " + textTransform);
}

// Verify the text Decoration
if (textDecoration.equals("underline")) {
    System.out.println("textDecoration is as expected.");
} else {
    System.out.println("textDecoration is not as expected. Found: " + textDecoration);
}
// Close the browser
driver.quit();

How to Retrieve Text and Background Colors with Selenium in Java

HOME

org.openqa.selenium.support.Color.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.Color;
import java.io.IOException;
import java.time.Duration;

public class Color_Example {

    public static void main(String args[]) throws IOException {

        String expectedColor = "#ffffff"; // White color in HEX

        ChromeOptions chromeOptions = new ChromeOptions();
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.manage().window().maximize();

        try {
            // Navigate to Url
            driver.get("https://www.selenium.dev/");

            WebElement element = driver.findElement(By.id("dev-partners"));

            // Retrieve the font color CSS property as RGBA
            String rgbaColor = element.getCssValue("color");
            System.out.println("rgbaColor : " + rgbaColor);

            // Convert the RGBA color to hex using the Color class
            String hexColor = Color.fromString(rgbaColor).asHex();
            System.out.println("hexColor : " + hexColor);

            // Convert the RGBA color to RGB using the Color class
            String rgbColor = Color.fromString(rgbaColor).asRgb();
            System.out.println("rgbColor : " + rgbColor);

            // Verify the color (example: verifying against expected #ffffff color)
            if (hexColor.equals(expectedColor)) {
                System.out.println("Hex color is as expected.");
            } else {
                System.out.println("Hex color is not as expected. Found: " + hexColor);
            }

        } finally {
            // Close the browser
            driver.quit();
        }
    }
}

 String expectedColor = "#ffffff"; // White color in HEX
ChromeOptions chromeOptions = new ChromeOptions();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
driver.get("https://www.selenium.dev/");
WebElement element = driver.findElement(By.id("dev-partners"));

// Retrieve the font color CSS property as RGBA
String rgbaColor = element.getCssValue("color");
System.out.println("rgbaColor : " + rgbaColor);
 // Convert the RGBA color to hex using the Color class
String hexColor = Color.fromString(rgbaColor).asHex();
System.out.println("hexColor : " + hexColor);

// Convert the RGBA color to RGB using the Color class
String rgbColor = Color.fromString(rgbaColor).asRgb();
System.out.println("rgbColor : " + rgbColor);
 // Verify the color (example: verifying against expected #ffffff color)
 if (hexColor.equals(expectedColor)) {
          System.out.println("Hex color is as expected.");
} else {
          System.out.println("Hex color is not as expected. Found: " + hexColor);
}
// Close the browser
driver.quit();

getCssValue("background-color")

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.Color;

import java.io.IOException;
import java.time.Duration;

public class BackgroundColor_Example {

    public static void main(String args[]) throws IOException {

        ChromeOptions chromeOptions = new ChromeOptions();
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.manage().window().maximize();

        try {
            // Navigate to Url
            driver.get("https://www.selenium.dev/");

            WebElement element = driver.findElement(By.id("dev-partners"));

            // Retrieve the background color CSS property
            String bgColorValue = element.getCssValue("background-color");
            System.out.println("color : " + bgColorValue);

            // Convert the background color to HEX format
            String hexColor = Color.fromString(bgColorValue).asHex();
            System.out.println("hexColor : " + hexColor);

            // Convert the background color to RGB format
            String rgbColor = Color.fromString(bgColorValue).asRgb();
            System.out.println("rgbColor : " + rgbColor);

            // Verify the color (example: verifying against expected #43b02a color)
            String expectedColor = "#43b02a"; // Green color in HEX
            if (hexColor.equals(expectedColor)) {
                System.out.println("Background color is as expected.");
            } else {
                System.out.println("Background color is not as expected. Found: " + hexColor);
            }
        } finally {
            // Close the browser
            driver.quit();
        }
    }
}

Performance Testing – Multiple Choice Questions and Answers – MCQ1

HOME

























JSON Handling and manipulation

HOME

XML Handling and manipulation

HOME

How to read XML using Java DOM Parser

HOME

An XML file contains data between the tags. This makes it complex to read compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:

How to retrieve tag name from XML?

<?xml version="1.0"?>
<employees>
    <employee id="1">
        <name>John William</name>
        <position>Software Engineer</position>
    </employee>
    <employee id="2">
        <name>Jane Smith</name>
        <position>Project Manager</position>
    </employee>
    <employee id="3">
        <name>Lilly Smith</name>
        <position>Product Owner</position>
    </employee>
</employees>

package XML.DOM;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

public class XMLParserTagNameExample {

    public static void main(String[] args) {
        try {
            // Create a DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // Obtain a DocumentBuilder from the factory
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            // Get the root element
            Element root = document.getDocumentElement();
            System.out.println("Root Element: " + root.getNodeName());
            System.out.println("-----------------------");

            // Retrieve the first employee element for extracting tag names
            NodeList nodeList = document.getElementsByTagName("employee");
            if (nodeList.getLength() > 0) {
                // If there is at least one employee, use it to print the element and attribute names
                Element employee = (Element) nodeList.item(0);

                    // Print the tag names
                    System.out.println("Employee ID Attribute Name: id");
                    System.out.println("Name Tag: " + employee.getElementsByTagName("name").item(0).getNodeName());
                    System.out.println("Position Tag: " + employee.getElementsByTagName("position").item(0).getNodeName());
                    System.out.println("-----------------------");
            }
        } catch (ParserConfigurationException e) {
            System.out.println("Parser configuration error occurred: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX parsing error occurred: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error when loading XML file: " + e.getMessage());
        } finally {
            System.out.println("XML parsing operation completed.");
        }
    }
}

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
 Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));
document.getDocumentElement().normalize();
Element root = document.getDocumentElement();
System.out.println("Root Element: " + root.getNodeName());
System.out.println("-----------------------");
NodeList nodeList = document.getElementsByTagName("employee");
            if (nodeList.getLength() > 0) {
                // If there is at least one employee, use it to print the element and attribute names
                Element employee = (Element) nodeList.item(0);

                    // Print the tag names
                    System.out.println("Employee ID Attribute Name: id");
                    System.out.println("Name Tag: " + employee.getElementsByTagName("name").item(0).getNodeName());
                    System.out.println("Position Tag: " + employee.getElementsByTagName("position").item(0).getNodeName());
                    System.out.println("-----------------------");
            }
        }

catch (ParserConfigurationException e) {
            System.out.println("Parser configuration error occurred: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX parsing error occurred: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error when loading XML file: " + e.getMessage());
        } finally {
            System.out.println("XML parsing operation completed.");
        }

package XML.DOM;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

public class SimpleXMLParserExample {

    public static void main(String[] args) {
        try {
            // Create a DocumentBuilderFactory
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            // Obtain a DocumentBuilder from the factory
            DocumentBuilder builder = factory.newDocumentBuilder();

            // Parse the XML file into a Document
            Document document = builder.parse(new File("src/test/resources/Payloads/SimpleXML.xml"));

            // Normalize XML structure
            document.getDocumentElement().normalize();

            // Get the root element
            Element root = document.getDocumentElement();
            System.out.println("Root Element: " + root.getNodeName());
            System.out.println("-----------------------");

            // Retrieve all employee nodes
            NodeList nodeList = document.getElementsByTagName("employee");

            // Iterate over the employee nodes
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element employee = (Element) node;

                    // Get the attribute and text content
                    String id = employee.getAttribute("id");
                    String name = employee.getElementsByTagName("name").item(0).getTextContent();
                    String position = employee.getElementsByTagName("position").item(0).getTextContent();

                    System.out.println("Employee ID: " + id);
                    System.out.println("Name: " + name);
                    System.out.println("Position: " + position);
                    System.out.println("-----------------------");
                }
            }
        } catch (ParserConfigurationException e) {
            System.out.println("Parser configuration error occurred: " + e.getMessage());
        } catch (SAXException e) {
            System.out.println("SAX parsing error occurred: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error when loading XML file: " + e.getMessage());
        } finally {
            System.out.println("XML parsing operation completed.");
        }
    }
}
NodeList nodeList = document.getElementsByTagName("employee");
 for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);

                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element employee = (Element) node;

                    // Get the attribute and text content
                    String id = employee.getAttribute("id");
                    String name = employee.getElementsByTagName("name").item(0).getTextContent();
                    String position = employee.getElementsByTagName("position").item(0).getTextContent();

                    System.out.println("Employee ID: " + id);
                    System.out.println("Name: " + name);
                    System.out.println("Position: " + position);
                    System.out.println("-----------------------");
                }
            }
        }

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Java – Multiple Choice Questions and Answers – Arrays

HOME




class array_output 
    {
        public static void main(String args[]) 
        {
            int array_variable [] = new int[10];
	        for (int i = 0; i < 10; ++i) 
            {
                array_variable[i] = i;
                System.out.print(array_variable[i] + " ");
                i++;
            }
        } 
   }


public class array_output {

    public static void main(String args[])
    {
        char array_variable [] = new char[10];
        for (int i = 0; i < 10; ++i)
        {
            array_variable[i] = 'i';
            System.out.print(array_variable[i] + "");
        }
    }
}

public class array_output {
    public static void main(String args[])
    {
        double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
        double result;
        result = 0;
        for (int i = 0; i < 6; ++i)
            result = result + num[i];
            System.out.print(result/6);

    }
}




public class Test {
    public static void main(String[] args) {
        String[] arr = {"Java", "Python", "C++"};
       System.out.println(arr[1]);
    }
}



public class Test {
    public static void main(String[] args) {
       int[] arr = new int[5];
      System.out.println(arr[1]);
    }
}

public class array_output {
    public static void main(String args[])
    {
        int[] arr = {1, 2, 3, 4};
        System.out.println(arr.length);
    }
}





public class array_output {
    public static void main(String args[])
    {
        int[] arr = {2, 4, 6, 8};
        System.out.println(arr[arr.length]);
    }
}

public class array_output {
    public static void main(String args[]) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i < arr.length; i++) {
            arr[i] = arr[i] * 2;
        }
        System.out.println(arr[2]);
    }
}

public class array_output {
    
    public static void main(String args[]) {
        int[] arr = {10, 20, 30, 40};
        System.out.println(arr[1] + arr[2]);
    }
}



Java – Multiple Choice Questions and Answers – Strings

HOME




class Test
    {
        public static void main(String args[]) 
        {
            int array_variable [] = new int[10];
	        for (int i = 0; i < 10; ++i) 
            {
                array_variable[i] = i;
                System.out.print(array_variable[i] + " ");
                i++;
            }
        } 
   }


public class Test {
    
    public static void main(String args[]) {
        String obj = "I" + "like" + "Java";
        System.out.println(obj);
    }
}

public class Test {
    
    public static void main(String args[]) {
        String obj = "I LIKE JAVA";
        System.out.println(obj.charAt(3));
    }
}

public class Test {

    public static void main(String args[]) {
        String obj = "I LIKE JAVA";
        System.out.println(obj.length());
    }
}

public class Test {

    public static void main(String args[]) {
        String obj = "hello";
        String obj1 = "world";
        String obj2 = obj;
        obj2 = " world";
        System.out.println(obj + " " + obj2);
    }
}

public class Test {

    public static void main(String args[]) {
        String obj = "hello";
        String obj1 = "world";
        String obj2 = "hello";
        System.out.println(obj.equals(obj1) + " " + obj.equals(obj2));
    }
}

public class Test {

    public static void main(String args[]) {
        System.out.println("Hello World".indexOf('W'));
    }
}



public class Test {

    public static void main(String args[]) {
        System.out.println("Java".compareTo("Java"));
    }
}

public class Test {

    public static void main(String args[]) {
        System.out.println("abc".substring(1, 3));
    }
}





public class Test {

    public static void main(String args[]) {
        System.out.println("abc".repeat(3));
    }
}

public class Test {

    public static void main(String args[]) {
        System.out.println("Hello".replace('e', 'a'));
    }
}

public class Test {

    public static void main(String args[]) {
        String s1 = new String("Hello");
        String s2 = new String("Hello");
        System.out.println(s1 == s2);
    }
}