XPaths - Yash-777/LearnJava GitHub Wiki

Find the child-siblink elements of an parent element, Untill other element comes.

Test XML:

<div id="one">
	<p>a</p>
	<p>b</p>
	<p>c</p>
	<h2> node type</h2>
	<p>d</p>
	<p>e</p>
</div>
<div id="two">
	<p>aa</p>
	<p>b</p>
	<label>This Is A Test</label>
	<p>c</p>
</div>

Out Put XPath using intersect:

//div[2]/child::p intersect //div[2]/child::*[name()!='p'][1]/preceding-sibling::p

Element followed by different class, whose count is 1

<tr class="other_label"></tr>
<tr class="other_label"></tr>
<tr class="facts_label"></tr>
<tr class="facts_label"></tr>
<tr class="other_label"></tr>    # Select this
<tr class="other_label"></tr>    # Select this
<tr class="facts_label"></tr>
<tr class="other_label"></tr>
<tr class="other_label"></tr>

Tested Xpath

//tr[ @class='other_label' and count(following-sibling::tr[@class='facts_label'])=1 ]

MyPost StackOverflow: Read XML file using XPathFactory, SAXParserFactory and StAX (JSR-173).

<dependency groupId:artifactId:version />
< wsdl4j:wsdl4j:1.6.2 />
< xalan:xalan:2.7.1 />
< xerces:xercesImpl:2.11.0 />
< net.sf.saxon:Saxon-HE:9.7.0-15 />
public final class XMLHelper { // /text(), /@id
    private final static Log log = LogFactory.getLog(XMLHelper.class);
    
    /**
     * Private constructor, so this class cannot be instantiated.
     */
    private XMLHelper() {
    }
    public static String encodeXMLSpecialChars(String str) {
        str = str.replaceAll("&", "&amp;"); // & --> &amp;
        str = str.replaceAll("<", "&lt;"); // < --> &lt;
        str = str.replaceAll(">", "&gt;"); // > --> &gt;
        str = str.replaceAll("'", "&apos;"); // ' --> &apos;
        str = str.replaceAll("\"", "&quot;"); // " --> &quot;
        return str;
    }
    public static String decodeXMLSpecialChars(String str) {
        str = str.replaceAll("&amp;", "&");
        str = str.replaceAll("&lt;", "<");
        str = str.replaceAll("&gt;", ">");
        str = str.replaceAll("&apos;", "'");
        str = str.replaceAll("&quot;", "\"");
        return str;
    }
    
    /**
     * Reader config = new FileReader(new File("D:/Yash/xmltest.xml"));
     * Document configuration = XMLHelper.parseReader(config);
     * 
     * Returns a DOM XML Document for a Reader. This method simply encapsulates
     * logistic overhead for building a parser, parse data and catch exceptions.
     * 
     * @param xmldata A reader containing the data.
     * @return DOM XML Document containing the data.
     */
    public static Document parseReader(Reader xmldata) {
        Document result = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            // factory.setIgnoringElementContentWhitespace(false);
            result = builder.parse(new InputSource(xmldata));
        } catch (Exception e) {
            throw new Error("Error while Parsing: " + e.getMessage(), e);
        }
        return result;
    }
    /**
     * Returns a DOM XML Document for a String. This method simply encapsulates
     * logistic overhead for building a parser, parse data and catch exceptions.
     * 
     * @param xml  the String to parse
     * @return an XML document as DOM tree.
     */
    public static Document parseString(String xml) {
        Document result = null;
        StringReader stringReader = null;
        InputSource source = null;
        DocumentBuilder builder = null;
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            stringReader = new StringReader(xml);
            source = new InputSource(stringReader);
            result = builder.parse(source);
        } catch (Exception e) {
            log.error(e, e);
        } finally {
            if (stringReader != null) {
                stringReader.close();
            }
            stringReader = null;
            source = null;
            builder = null;
        }
        return result;
    }
    
    public static String toString(Node document, boolean omitXmlDeclaration) throws TransformerException, IOException {
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = (SAXTransformerFactory) new net.sf.saxon.TransformerFactoryImpl();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration ? "yes" : "no");
        transformer.transform(new DOMSource(document), streamResult);
        String outputStr=stringWriter.toString();
        stringWriter.close();
        return outputStr;
    }

    public static String getXmlContentAsString(Node node) throws TransformerException, IOException {
        StringBuilder stringBuilder = new StringBuilder();
        NodeList childNodes = node.getChildNodes();
        int length = childNodes.getLength();
        for (int i = 0; i < length; i++) {
            stringBuilder.append(toString(childNodes.item(i), true));
        }
        return stringBuilder.toString();
    }

    public static Node getNode(Node context, String xpath) {
        Node result = null;
        try {
            result = XPathAPI.selectSingleNode(context, xpath);
        } catch (TransformerException e) {
            throw new Error("TransformerException: " + e.getMessage(), e);
        }
        return result;
    }
    public static String getNodeAsString(Node context, String xpath) {
        Node node = getNode(context, xpath);
        String result = null;
        if (node == null) {
            result = null;
        } else {
            result = node.getNodeValue();
        }
        return result;
    }
    
    public static NodeList getNodesList(Node context, String xpath) {
        NodeList result = null;
        try {
            result = XPathAPI.selectNodeList(context, xpath);
        } catch (TransformerException e) {
            throw new Error("TransformerException: " + e.getMessage(), e);
        }
        return result;
    }

    public static Map getValuesMap(Node context, String xpath, String keyTag, String valueTag) {
        NodeList nl = XMLHelper.getNodesList(context, xpath);
        Map values = new LinkedHashMap<>();
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            String value = XMLHelper.getNodeAsString(n, "@" + valueTag);
            String key = XMLHelper.getNodeAsString(n, "@" + keyTag);
            values.put(key, value);
        }
        return values;
    }

    public static String extractTextFromXml(String xml) {
        String result = xml.replaceAll("<[^>]+>", "");
        return result.replaceAll("\\s+", " ").trim();
    }

    public static String serializeXML(Document doc, boolean indent, boolean omitXmlDeclaration) {
        Transformer transformer;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
            if (indent)
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            if (omitXmlDeclaration)
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            // initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
            String xmlString = result.getWriter().toString();
            return xmlString;
        } catch (Exception e) {
            throw new Error("XML Library malfunction: " + e.getMessage(), e);
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️