Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        String xml = "<?xml version='1.0' encoding='UTF-8'?>" + "<Employees>"
                + "  <Employee emplid='1' type='admin'>" + "    <firstname/>" + "    <lastname>A</lastname>"
                + "    <age>30</age>" + "    <email>j@s.com</email>" + "  </Employee>"
                + "  <Employee emplid='2' type='admin'>" + "    <firstname>S</firstname>"
                + "    <lastname>H</lastname>" + "    <age>32</age>" + "    <email>s@h.com</email>"
                + "  </Employee>" + "</Employees>";
        List<String> ids = Arrays.asList("1", "2");
        for (int i = 0; i < ids.size(); i++) {
            String employeeId = ids.get(i);
            String xpath = "/Employees/Employee[@emplid='" + employeeId + "']/firstname";
            XPath xPath = XPathFactory.newInstance().newXPath();
            String employeeFirstName = xPath.evaluate(xpath, new InputSource(new StringReader(xml)));
            if (employeeFirstName == "") {
                System.out.println("Employee " + employeeId + " has no first name.");
            } else {
                System.out.println("Employee " + employeeId + "'s first name is " + employeeFirstName);
            }
        }
    }
}