Java HTML / XML How to - Distinguish two Xml Elements by missing tag








Question

We would like to know how to distinguish two Xml Elements by missing tag.

Answer

import java.io.ByteArrayInputStream;
import java.io.InputStream;
/*ww  w.ja v a2  s . c o  m*/
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());
    }
  }
}