0

I want to iterate XPath to get only table name. Here is my Xpath value.

PromoteData/Table[@Id='auditSet']/Table[@Id='auditSetMapping']/Table[@Id='appExpr']

Please guide me how to iterate each value of this XPath. The expected output would be like 'auditSet', 'auditSetMapping', 'appExpr'

Andrew Barber
  • 37,547
  • 20
  • 91
  • 118
  • Duplicated from http://stackoverflow.com/questions/4835891/how-to-extract-attributes-value-through-xpath – aalku Feb 07 '14 at 13:10
  • Why do you insist on editing out the sample xpath value? The question doesn't make much sense without it. For anyone else coming to this question, it's available in the edit history. – Krease Feb 12 '14 at 06:46
  • There is no basis whatsoever to delete this post, and it's unfair to the person who helped you to even want to do so. It's also not proper to edit out your code. I have reverted it back. *Do not do this again*. – Andrew Barber Feb 12 '14 at 15:28

1 Answers1

1
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

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


public class XPathExtract {

  public static void main(String[] args) throws SAXException, IOException,
      ParserConfigurationException, XPathExpressionException {
    String xml = "...";

    // Parse the XML as DOM
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        .parse(new InputSource(new StringReader(xml)));

    // Create a XPath instance
    XPath xpath = XPathFactory.newInstance().newXPath();

    // Evaluate the XPath. The result is a NodeList
    NodeList nodes = (NodeList) xpath.evaluate(
      "PromoteData/Table[@Id='auditSet']/Table[@Id='auditSetMapping']/Table[@Id='appExpr']", 
        doc, XPathConstants.NODESET);

    // Iterate over the nodes
    for (int i = 0; i < nodes.getLength(); i++) {
      // node.item(i) is a Node. If you are sure, it is always an Element you can do a cast
      Element el = (Element) nodes.item(i);
      // Process the element
      System.out.println(el.getAttribute("Id"));
    }
  }
}
vanje
  • 9,404
  • 2
  • 31
  • 41
  • thanks vanje, but this code is printing only 1 value ie appExprr, I want the output as auditset, auditsetmapping, appExpr – user3275223 Feb 07 '14 at 20:02
  • Maybe you should adjust your XPath expression. But you didn't provide an example of your XML, so it is very difficult to check if your XPath expression fits your needs. – vanje Feb 08 '14 at 19:30