Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] args) throws Exception {
        String xml = "<root>" + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.75</cgc:PriceAmount>"
                + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>" + "</ctc:BasePrice>"
                + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.25</cgc:PriceAmount>"
                + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>"
                + "<cgc:MinimumQuantity quantityUnitCode='EA'>3</cgc:MinimumQuantity>" + "</ctc:BasePrice>"
                + "</root>";

        InputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(xmlStream);
        XPath xPath = XPathFactory.newInstance().newXPath();
        String expression = "//*[local-name() = 'BasePrice' and not(descendant::*[local-name() = 'MinimumQuantity'])]/*[local-name()='PriceAmount']";
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
        }
    }
}