read xml nodes using java code - java

i am connecting to database of many servers to retrieve data from them all, i am using xml file contains the information of each database server [ip,port,user,passwd] followed by the query to be executed on that server. i read the queries in my code as arrayList and get them one by one to be processed. what i need is a clear simple code to also read the database server info to connect to it and execute the relative query , i.e. for each a query i need to get the database IP,port,user,passwd in my code. here is my xml file structure. thanks in adavnce.
<?xml version="1.0"?>
<Database>
<DB>
<ip></ip>
<port></port>
<user></user>
<pass></pass>
</DB>
<Query>
select date from myTable
</Query>
<DB>
<ip></ip>
<port></port>
<user></user>
<pass></pass>
</DB>
<Query>
select time from myTable
</Query>
<DB>
<ip></ip>
<port></port>
<user></user>
<pass><></pass>
</DB>
<Query>
select name from myTable
</Query>
</Database>

You can use Java's DOM api for xml processing and xpath.
DOM: https://docs.oracle.com/javase/tutorial/jaxp/dom/index.html
Xpath: http://www.w3schools.com/xsl/xpath_syntax.asp
Below is some sample code that does part of what you want (extracts the ip and port). You will need to modify it to do the rest:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomTester {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
InputStream inStr = null;
try {
String xml = "<?xml version=\"1.0\"?>"
+ "<Database>"
+ "<DB>"
+ "<ip>666</ip>"
+ "<port>7</port>"
+ "</DB>"
+ "<DB>"
+ " <ip>13</ip>"
+ "<port>1</port>"
+ "</DB>"
+ "</Database>";
inStr = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inStr);
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath.compile("/Database");
Element databaseEl = (Element)expr.evaluate(doc, XPathConstants.NODE);
NodeList databaseNodeList = databaseEl.getChildNodes();
for (int ii=0; ii<databaseNodeList.getLength(); ++ii) {
Node dbNode = databaseNodeList.item(ii);
XPathExpression ipExpr = xpath.compile("ip");
Element ipElement = (Element)ipExpr.evaluate(dbNode, XPathConstants.NODE);
String ip = ipElement.getTextContent();
XPathExpression portExpr = xpath.compile("port");
Element portEl = (Element)portExpr.evaluate(dbNode, XPathConstants.NODE);
String port = portEl.getTextContent();
System.out.println("DB node[" + ii + "] = ip: " + ip + " port: " + port);
}
} finally {
if (null != inStr) {
inStr.close();
}
}
}
}
Since you are reading from a file instead of using a string, instead of doing this:
inStr = new ByteArrayInputStream(xml.getBytes());
do this:
File f = new File("your/file/path.xml");
inStr = new FileInputStream(f);

Related

XPathFactoryImpl not able to identify the root node if xml doc contains the namesapcecontext

I am quite new to XML and Saxon API's, Here I am using Saxon 10.3 HE jar to extract the data from the XML file. Here I want to extract the country attribute from the active country_information node where I am using the date functions.
Sample input XML :
<person xmlns="urn:my.poctest.com">
<country_information>
<country>FRA</country>
<end_date>9999-12-31</end_date>
<start_date>2009-12-01</start_date>
</country_information>
<country_information>
<country>FRA</country>
<end_date>9999-12-31</end_date>
<start_date>2009-12-01</start_date>
</country_information>
</person>
Code :
import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFactoryConfigurationException;
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;
import net.sf.saxon.xpath.XPathFactoryImpl;
public class SaxonPoc {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException,
XPathExpressionException, XPathFactoryConfigurationException {
String xml = " <person xmlns=\"urn:my.poctest.com\">\r\n"
+ " <country_information>\r\n"
+ " <country>FRA</country>\r\n"
+ " <end_date>9999-12-31</end_date>\r\n"
+ " <start_date>2020-02-24</start_date>\r\n"
+ " </country_information>\r\n"
+ " <country_information>\r\n"
+ " <country>USA</country>\r\n"
+ " <end_date>2020-02-23</end_date>\r\n"
+ " <start_date>2009-12-01</start_date>\r\n"
+ " </country_information> \r\n"
+ " </person>";
Document doc = SaxonPoc.getDocument(xml, false);
NodeList matches = (NodeList) SaxonTest.getXpathExpression("//person", null).evaluate(doc,
XPathConstants.NODESET);
if (matches != null) {
Element node = (Element) matches.item(0);
XPath xPath1 = SaxonPoc.getXpath(null);
String xPathStatement = "/person/country_information[xs:date(start_date) le current-date() and xs:date(end_date) ge current-date()]/country";
NodeList childNodes = (NodeList) xPath1.evaluate(xPathStatement, node, XPathConstants.NODESET);
if (childNodes.getLength() > 0) {
String nodeName = childNodes.item(0).getFirstChild().getNodeName();
System.out.println("Node :" + nodeName);
String value = childNodes.item(0).getTextContent();
System.out.println("Country Name :" + value);
}
}
System.out.println("Finished");
}
public static Document getDocument(String xml, boolean isNamespaceAware)
throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(isNamespaceAware);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
public static XPath getXpath(Map<String, String> namespaceMappings) throws XPathFactoryConfigurationException {
XPathFactory xpathFactory = new XPathFactoryImpl();
XPath xpath = xpathFactory.newXPath();
NamespaceContext nsc = new NamespaceContext() {
#Override
public String getNamespaceURI(String prefix) {
return (null != namespaceMappings) ? namespaceMappings.get(prefix) : null;
}
#Override
public String getPrefix(String namespaceURI) {
return null;
}
#Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
};
xpath.setNamespaceContext(nsc);
return xpath;
}
public static XPathExpression getXpathExpression(String xpathExpr, Map<String, String> namespaceMappings)
throws XPathExpressionException, XPathFactoryConfigurationException {
XPath xpath = getXpath(namespaceMappings);
return xpath.compile(xpathExpr);
}
}
I am facing a null pointer as it is not able to find the root node person an XML doc. If I remove the xmlns="urn:my.poctest.com" then it is able to get the root path but in a later stage, it is failing with javax.xml.xpath.XPathExpressionException: net.sf.saxon.trans.XPathException: Namespace prefix 'xs' has not been declared. If I remove the namespace from XML doc and NamespaceContext implementation from code then it is working fine. But here actually I don't want to remove both things.
Can someone point out me here, what I am doing wrong? Thanks in advance!!
You might like to know that recent versions of Saxon include the option to do
((net.sf.saxon.xpath.XPathEvaluator)XPath).getStaticContext()
.setUnprefixedElementMatchingPolicy(
UnprefixedElementMatchingPolicy.ANY_NAMESPACE))
which causes an unprefixed element name in your XPath expression to match on local name alone, regardless of the namespace.
This was mainly introduced for HTML, where there is complete confusion as to whether elements in an HTML DOM are in a namespace or not; but it's useful more generally where you really don't care about the namespaces and just wish they weren't there to make your life a misery.

How to parse the full content of a XML Tag in java

I have some kind of complex XML data structure. The structure contains different fragments like in the following example:
<data>
<content-part-1>
<h1>Hello <strong>World</strong>. This is some text.</h1>
<h2>.....</h2>
</content-part1>
....
</data>
The h1 tag within the tag 'content-part-1' is of interest. I want to get the full content of the xml tag 'h1'.
In java I used the javax.xml.parsers.DocumentBuilder and tried something like this:
String my_content="<h1>Hello <strong>World</strong>. This is some text.</h1>";
// parse h1 tag..
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = documentBuilder.parse(new InputSource(new StringReader(my_content)));
Node node = doc.importNode(doc.getDocumentElement(), true);
if (node != null && node.getNodeName().equals("h1")) {
return node.getTextContent();
}
But the method 'getTextContent()' will return:
Hello World. This is some text.
The tag "strong" is removed by the xml parser (as it is the documented behavior).
My question is how I can extract the full content of a single XML Node within a org.w3c.dom.Document without any further parsing the node content?
Although java DOM parser provides functionality for parsing mixed content, in this particular case it could be more convenient to use Jsoup library. When using it code to extract h1 element content would be as follows:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
String text = "<data>\n"
+ " <content-part1>\n"
+ " <h1>Hello <strong>World</strong>. This is some text.</h1>\n"
+ " <h2></h2>\n"
+ " </content-part1>\n"
+ "</data>";
Document doc = Jsoup.parse(text);
Elements h1Elements = doc.select("h1");
for (Element h1 : h1Elements) {
System.out.println(h1.html());
}
Output in this case will be "Hello <strong>World</strong>. This is some text."
What you probaly want is XML generation from some subnode of your document.
So with slighlty modified nodeToString from earlier answer to similar question I can propose to
generate text <h1>Hello <strong>World</strong>. This is some text.</h1>. Some extra effor might be needed to get rid of <h1> and </h1>
package com.github.vtitov.test;
import org.junit.Test;
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.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class XmlTest {
#Test
public void buildXml() throws Exception {
String my_content="<h1>Hello <strong>World</strong>. This is some text.</h1>";
// parse h1 tag..
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = documentBuilder.parse(new InputSource(new StringReader(my_content)));
Node node = doc.importNode(doc.getDocumentElement(), true);
String h1Content = null;
if (node != null && node.getNodeName().equals("h1")) {
h1Content = nodeToString(node);
}
assertThat("h1", h1Content, equalTo("<h1>Hello <strong>World</strong>. This is some text.</h1>"));
}
private static String nodeToString(Node node) throws TransformerException {
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "no");
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
}
}

How to make dynamic kml from java

I am new to KML I have to make a KML file that contains some information about a place and that data should be displayed in Google map. I have written a code in java which will generate a KML as an output but I have some problem, the KML is not generating.
java.io.FileNotFoundException: c:\PlaceMarkers.kml (Access is denied) this is my error..
This is what I have done so far..
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class GenKMLPlaceMarker {
public int id;
public String name;
public String address;
public float lat;
public float lng;
public String type;
public static void main(String[] args) {
Statement stmt;
ResultSet rs;
GenKMLPlaceMarker KML = new GenKMLPlaceMarker();
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/homeland";
Connection con = DriverManager.getConnection(url, "root", "root");
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Document doc = builder.newDocument();
Element root = doc.createElement("kml");
root.setAttribute("xmlns", "http://earth.google.com/kml/2.1");
doc.appendChild(root);
Element dnode = doc.createElement("Document");
root.appendChild(dnode);
Element rstyle = doc.createElement("Style");
rstyle.setAttribute("id", "restaurantStyle");
Element ristyle = doc.createElement("IconStyle");
ristyle.setAttribute("id", "restaurantIcon");
Element ricon = doc.createElement("Icon");
Element riconhref = doc.createElement("href");
riconhref
.appendChild(doc
.createTextNode("http://maps.google.com/mapfiles/kml/pal2/icon63.png"));
rstyle.appendChild(ristyle);
ricon.appendChild(riconhref);
ristyle.appendChild(ricon);
dnode.appendChild(rstyle);
Element bstyle = doc.createElement("Style");
bstyle.setAttribute("id", "barStyle");
Element bistyle = doc.createElement("IconStyle");
bistyle.setAttribute("id", "barIcon");
Element bicon = doc.createElement("Icon");
Element biconhref = doc.createElement("href");
biconhref
.appendChild(doc
.createTextNode("http://maps.google.com/mapfiles/kml/pal2/icon27.png"));
bstyle.appendChild(bistyle);
bicon.appendChild(biconhref);
bistyle.appendChild(bicon);
dnode.appendChild(bstyle);
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM markers");
while (rs.next()) {
KML.id = rs.getInt("id");
KML.name = rs.getString("name");
KML.address = rs.getString("address");
KML.lat = rs.getFloat("lat");
KML.lng = rs.getFloat("lng");
KML.type = rs.getString("type");
Element placemark = doc.createElement("Placemark");
dnode.appendChild(placemark);
Element name = doc.createElement("name");
name.appendChild(doc.createTextNode(KML.name));
placemark.appendChild(name);
Element descrip = doc.createElement("description");
descrip.appendChild(doc.createTextNode(KML.address));
placemark.appendChild(descrip);
Element styleUrl = doc.createElement("styleUrl");
styleUrl.appendChild(doc.createTextNode("#" + KML.type
+ "Style"));
placemark.appendChild(styleUrl);
Element point = doc.createElement("Point");
Element coordinates = doc.createElement("coordinates");
coordinates.appendChild(doc.createTextNode(KML.lng + ","
+ KML.lat));
point.appendChild(coordinates);
placemark.appendChild(point);
}
Source src = new DOMSource(doc);
Result dest = new StreamResult(new File("c:/PlaceMarkers.kml"));
aTransformer.transform(src, dest);
System.out.println("Completed.....");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
You can use Java API for KML
The objective of the Java API for KML is to provide Java interfaces for easy access to KML (Keyhole Markup Language) data.
The main goal of the Java API for KML (JAK) is to provide automatically generated full reference implementation of the KML object model defined by OGC’s KML standard and Google’s GX extensions. It is an object orientated API that enables the convenient and easy use of KML in existing Java environments.

Java Web Service & XML

I would need to build a simple program for my homework purposes that will retrieve data from an XML attribute based on the user input in a web service. To that end, I assumed I would start building a class that could parse my XML string and also I built a simple java service that does nothing but responds with a simple message. The problem is how do I put these together in order to get my program to work? Is this a good way to begin with? Please advise.
Also, to make thing a little more easier, the data in the string representation of XML has key words in both English and Serbian that would enable this web service to retrieve from one another:
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class Recnik {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE language [<!ATTLIST phrase id ID #IMPLIED>]><language id=\"sr\"><phrase key=\"house\" value=\"kuca\"/><phrase key=\"dog\" value=\"pas\"/><phrase key=\"cat\" value=\"macka\"/></language>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//FileInputStream fis = new FileInputStream("myBooks.xml");
InputSource is = new InputSource(new StringReader(xmlString));
Document doc = db.parse(is);
Element r = doc.getDocumentElement();
NodeList language = r.getElementsByTagName("phrase");
System.out.println(language.item(1).getAttributes().item(0).getTextContent());
}
}
package Prevodilac;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
#WebService(serviceName = "Prevodilac")
public class Prevodilac {
#WebMethod(operationName = "pretraga")
public String pretraga(int a, int b) {
Integer res = a+b;
return res.toString();
}
}
#WebService(serviceName = "Prevodilac")
public class Prevodilac {
Document doc;
public Prevodilac() throws ParserConfigurationException, SAXException, IOException{
// Fill the document just once, not for each method call
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE language [<!ATTLIST phrase id ID #IMPLIED>]><language id=\"sr\"><phrase key=\"house\" value=\"kuca\"/><phrase key=\"dog\" value=\"pas\"/><phrase key=\"cat\" value=\"macka\"/></language>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlString));
doc = db.parse(is);
}
#WebMethod(operationName = "pretraga")
public String pretraga(String key) {
Element r = doc.getDocumentElement();
NodeList language = r.getElementsByTagName("phrase");
String result = "Not found";
for( int index = 0; index < language.getLength(); index++ ) {
Node attribute = language.item(index).getAttributes().getNamedItem("key");
// TODO (It's homework after all):
// check if the attribute corresponds to key parameter
if( attribute..... ){
// fill result with attribute value
result = ...;
}
}
return result;
}
}

XML Parser and xpath expression

I am using java default documentbuilder to parse a xml document which has less than 100 lines of code . It will take 35 milliseconds to parse a document , a single xpath expression takes 15 milliseconds to execute . How can I optimize the time taken for both xml and parser? .
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
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.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XMLParser {
public static final Logger LOGGER = Logger.getLogger(XMLParser.class.getName());
private Map<String,List<NamedNodeMap>> fileVsProperties = new HashMap<String, List<NamedNodeMap>>();
private Document document;
public XMLParser(File file){
this.document = XMLUtil.getDocument(file);
}
public void setProperties(Element file){
NodeList properties = file.getElementsByTagName("property");
List<NamedNodeMap> props = new ArrayList<NamedNodeMap>();
String type = file.getAttribute("type");
String path = file.getAttribute("path");
if("".equals(path)){
LOGGER.log(Level.INFO,"Attribute path is required for a file.");
return;
}
path = path+":"+type;
for(int i = 0;i<properties.getLength();i++){
Element property = (Element) properties.item(i);
props.add(property.getAttributes());
}
setProperties(props,path);
}
private void setProperties(List<NamedNodeMap> properties , String path){
List<NamedNodeMap> previousValue = fileVsProperties.get(path);
if(previousValue != null){
previousValue.addAll(properties);
}else{
fileVsProperties.put(path,properties);
}
}
public Element getConfiguration(String branchName) throws XPathExpressionException{
return (Element)XMLUtil.getElements("/configurations/configuration[#name='"+branchName+"']",document.getDocumentElement(),XPathConstants.NODE);
}
public static void main(String[] args) throws XPathExpressionException {
long start = System.currentTimeMillis();
File doc = new File("install.xml");
XMLParser parser = new XMLParser(doc);
long end = System.currentTimeMillis();
System.out.println("Time Taken For Parsing :: "+ (end-start) + " milliseconds");
start = end;
Element configuration = parser.getConfiguration("BHARATHIKANNAN");
end = System.currentTimeMillis();
System.out.println("Time Taken For XPATH Expression TO Finding the Configuration :: "+ (end-start) + " milliseconds");
start = end;
NodeList files = parser.getFiles(configuration);
for(int i=0;i<files.getLength();i++){
parser.setProperties((Element) files.item(i));
}
end = System.currentTimeMillis();
System.out.println(parser.fileVsProperties);
System.out.println("Time Taken For Setting Properties :: "+ (end-start) + " milliseconds");
}
public NodeList getFiles(Element configuration){
return configuration.getElementsByTagName("file");
}
}
class XMLUtil{
private static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
private static DocumentBuilder builder;
public static final Logger LOGGER = Logger.getLogger(XMLUtil.class.getName());
private static XPathFactory xpathFactory = XPathFactory.newInstance();
private static XPath xpath;
static {
try {
builder = factory.newDocumentBuilder();
xpath = xpathFactory.newXPath();
} catch (ParserConfigurationException e) {
LOGGER.log(Level.INFO,"");
}
}
public static Document getDocument(File f){
Document doc = null;
try {
doc = builder.parse(f);
} catch (SAXException e) {
LOGGER.log(Level.WARNING,"Invalid XML Document ",e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"No Document Found in the given path",e);
}
return doc;
}
public static Object getElements(String xpathExpression , Element ele ,QName dataType) throws XPathExpressionException{
return xpath.evaluate(xpathExpression, ele,dataType);
}
}
XML File
<?xml version="1.0"?>
<!--
Note : Default configuration loaded using your current branch name . You can extend configurations using extend attribute in configuration
node .
-->
<configurations>
<configuration name="default">
<files>
<file type="xml" path="conf/server.xml.orig">
<property regex="(port=).*" replace="\18080" xpath="/Server/Connector"></property>
<property regex="(port=).*" replace="\18080"></property>
</file>
<file type="text" path="conf/system_properties.conf">
<property regex="(username=).*" replace="\1root" ></property>
</file>
</files>
</configuration>
<configuration name="BHARATHIKANNAN" extends="default">
<files>
<file type="text" path="conf/system_properties.conf">
<property regex="(username=).*" replace="\1root" ></property>
</file>
</files>
</configuration>
</configurations>
Output :
Time Taken For Parsing :: 24 milliseconds
Time Taken For XPATH Expression TO Finding the Configuration :: 14 milliseconds
{conf/system_properties.conf:text=[com.sun.org.apache.xerces.internal.dom.AttributeMap#75d9fd51]}
Time Taken For Setting Properties :: 0 milliseconds
Someone asked recently about a very similar task but with a much larger document (2Mb), and I gave some Saxon timings here:
https://stackoverflow.com/questions/12497928/xpath-speed-comparision/12508614#12508614
These timings are much faster than you are seeing, on a much larger document. Since you are already using Java, switching to Saxon should be very straightforward.
One caveat though is that you start your timings immediately on entry to main() which means you are mainly measuring class loading time rather than XML processing time. My measurements took care to warm up the Java VM before measurement started.
Note that if you're using Saxon, it's best by far to use Saxon's native tree model rather than DOM or other alternatives. We recently published some measurements here:
http://dev.saxonica.com/blog/mike/2012/09/index.html#000194
DOM comes out 8 times worse than Saxon's native tree on average, 23 times worse in the worst case.

Categories