Wednesday, September 14, 2011

XPath Tutorial


Hi All,
Please i have small description of the XPath Parser usage in Java instead of the DOM or SAX parsers. The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value.



Below i have written  a Simple XPath Tutorial program in java
import javax.xml.xpath.*;

public static void main(String args[]){
          String xmlString = "<employees>"+
                                         "<employee> "+
"<name>"+
"Johny"+
"</name>"+
"<name>"+
"Williams"+
"</name>"+
"</employee>"+
"</employees>" ;
try{
//To get an instance of the XPathFactory object itself.

XPathFactory xPathFactory = XPathFactory.newInstance();
// Create an instance of XPath from the factory class

XPath xPath = xPathFactory.newXPath();
String expression = "/employees/employee/name";
// Compile the expression to get a XPathExpression object.
XPathExpression xpathExpression = xPath.compile(expression);
//Evaluate the expression against the XML Document to get the result.
Object result = xpathExpression.evaluate(new InputSource(new StringReader(xmlString)));


}catch(XPathExpressionException e){
e.printStackTrace();
}
}


The above program will give the name of all the employees in the xml Document.

  • If at all you need only the first employee name pass the expression value as :-

                  String expression = "/employees/employee[1]/name"; 
                  will return only the first employee name.

  • If you need to pass a document instead of an xmlString then follow the below process for reading the xml document.
       String  xmlFile = "TestFile.xml";
        Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
At the lat pass the only xmlDocument to evaluate() method instead of 
xmlString See Below:-
xPathExpression.evaluate(xmlDocument, returnType);
//returnType can be any of the QNames available in XPath Package:-
//XPathConstants.STRING, XPathConstants.NUMBER, XPathConstants.BOOLEAN, 
//XPathConstants.NODE and XPathConstants.NODESET. 

                              OR
      XPathReader reader = new XPathReader("src\\com\\javabeat\\tips\\xpath\\projects.xml"); 
reader.read(expression, XPathConstants.STRING)

// To get a xml attribute.
String expression = "/projects/project[1]/@id";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get a child element's value.
expression = "/projects/project[2]/name";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get an entire node
expression = "/projects/project[3]";
NodeList thirdProject = (NodeList)reader.read(expression,
XPathConstants.NODESET);
traverse(thirdProject);

public static void traverse(NodeList rootNode){
for(int index = 0; index < rootNode.getLength();index ++){
Node aNode = rootNode.item(index);
if (aNode.getNodeType() == Node.ELEMENT_NODE){
NodeList childNodes = aNode.getChildNodes();
if (childNodes.getLength() > 0){
System.out.println("Node Name-->" + aNode.getNodeName() +" , Node Value-->" + aNode.getTextContent());
}
traverse(aNode.getChildNodes());
}
}
}



Tuesday, September 6, 2011

Creation Of PDF Document in JAVA

Here i'm giving a simple program for creating a pdf document using java.
Prerequsite jars are :-
iText.jar


Remark:
  1. Once a document is created you can add some meta information.
  2. You can also set the headers/footers.
  3. You have to open the document before you can write content.
  4. You can only write content (no more meta-formation!) once a document is opened.
  5. When you change the header/footer on a certain page, this will be effective starting on the next page.
  6. After closing the document, every listener (as well as its OutputStream) is closed too.
Below is the main program:-
import com.itextpdf.text.*;

public class DataIntoPDF{


public static void main(String args[]){
//create a document
Document PDFDocument = new Document(PageSize.A4,50,50,50,50);
try{
//pdfwriter instance for writing the data to a file.FileOutput writes the data using output stream to the file specified.If the file doesn't exists throws file not found exception.
PdfWriter pdfWriter  = PdfWriter.getInstance(PDFDocument, new FileOutputStream("E:/pdfData.pdf"));
//add meta information to document
pDFDocument.addAuthor("Anand Kumar");
pDFDocument.addCreator("Anand Kumar");
pDFDocument.addSubject("PDF Creation");
pDFDocument.addCreationDate();
pDFDocument.addTitle("PDf Creation");
PDFDocument.open();
                        String dataToPDF  = 
                                        "Anand Kumar,
                                            " +
 Information only
                                           " +
"Nothing Confidential," +
"
                                                   Just Follow,
                                                  " +
"
                                     Address– " +
"Not Mine Write your Own 
                                      ";

Paragraph p = new Paragraph(dataToPDF);
PDFDocument.add(p);
//Adds a new page to the existing document
PDFDocument.newPage();
Image image = getImageFromResource("/PathtoImage/ImageFile");
Chunk imageChunk = new Chunk(image,-5,0);
PDFDocument.add(imageChunk);
}catch(DocumentException de){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
PDFDocument.close();

}


//For Image resource
private static Image getImageFromResource(String URI){
Image image = null;
try{
image = Image.getInstance(URI);
}catch(IOException ioe){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return image;
}


}

If any modifications are appreciated.
Thankyou.......................!!!!!!!!!!!!!!!!:-)