Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class Main {

    public static void main(String[] args) throws Exception {
        String xml = "<company><year id='2000'><quarter id='1' sales='80'/></year><year id='2001'><quarter id='1' sales='20'/></year></company>";
        String xpath = "/company/year[@id=2001]";
        XPath xPath = XPathFactory.newInstance().newXPath();
        Node node = (Node) xPath.evaluate(xpath, new InputSource(new StringReader(xml)), XPathConstants.NODE);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(node), new StreamResult(System.out));
    }

}