Thursday 16 February 2017

Read soap xml file using xpath



import org.apache.xmlbeans.impl.xb.xsdschema.FieldDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

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 java.io.FileReader;


public class SoapReaderUsingXpath {
    public static void main(String[] args){
        String result ="";
        String soapXmlFile;
        DocumentBuilderFactory dbf;
        DocumentBuilder db;
        Document doc;
        XPath xpath;
        Node nl;
        soapXmlFile="C:\\wssoap.xml";
        String myXpath="//Element/Body/Node1/text()";
        try{
            dbf=DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(false);
            db=dbf.newDocumentBuilder();
            doc=db.parse(new InputSource(new FileReader(soapXmlFile)));
            xpath= XPathFactory.newInstance().newXPath();
            nl=(Node)xpath.evaluate(myXpath,doc.getDocumentElement(), XPathConstants.NODE);
            result=nl.getNodeValue();
        }
        catch (Exception ex){}

    }
}

Read text file?




BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}