News:

Loading...

FoodForFutureGeeks

Thursday, 2 May 2013

XML Writer In C++ using Xerces-DOM

The following program demonstrates how to write an XML file in C++:


/*********************************
* author: Aniruddha S N
*
* description:
* The main function uses a DOM implementation 
* to construct a DOM tree, once the dom tree is completely constructed
* it invokes the mserialiser_XML_Writer method to Serilize the DOM tree
* and write it to a xml file.
*
* Dependency: xerces3.1-c (code not compatible with older versions of xerces.)
*/
 
 
#include<iostream>
#include<vector>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/StdOutFormatTarget.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <time.h>
#include <string>
#include <sstream>
void Serialiser_XML_writer(xercesc::DOMDocument* pDOMDocument, char* FullFilePath );
 
using namespace std;
//below macro gives all the required namespaces for Xerces
XERCES_CPP_NAMESPACE_USE
 
 
 
 
 
 
 
 
void main()
{
 
XMLPlatformUtils::Initialize();
 
// Pointer to our DOMImplementation.
DOMImplementation * pDOMImplementation = NULL;
 
// Get the DOM Implementation (used for creating DOMDocuments).
// Also see: http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html
pDOMImplementation = 
  DOMImplementationRegistry::getDOMImplementation(XMLString::transcode("core"));
 
DOMDocument * pDOMDocument = NULL;
 
pDOMDocument = pDOMImplementation-&gt;createDocument(L"schemas.example.com/2008/", 
                                                  L"ex:Hello_World", 0);
 
 
DOMElement * pRootElement = NULL;
pRootElement = pDOMDocument-&gt;getDocumentElement();
 
 
// Create a Comment node, and then append this to the root element.
DOMComment * pDOMComment = NULL;
pDOMComment = pDOMDocument-&gt;createComment(L"Dates are formatted mm/dd/yy." 
              L" Don't forget XML is case-sensitive.");
pRootElement-&gt;appendChild(pDOMComment);
 
 
// Create an Element node, then fill in some attributes,
// and then append this to the root element.
DOMElement * pDataElement = NULL;
pDataElement = pDOMDocument-&gt;createElement(L"data");
 
    // Copy the current system date to a buffer, then set/create the attribute.
    wchar_t wcharBuffer[128];
    _wstrdate_s(wcharBuffer, 9);
    pDataElement-&gt;setAttribute(L"date", wcharBuffer);
 
    // Convert an integer to a string, then set/create the attribute.
    _itow_s(65536, wcharBuffer, 128, 10);
    pDataElement-&gt;setAttribute(L"integer", wcharBuffer);
 
    // Convert a floating-point number to a wstring,
    // then set/create the attribute.
    std::wstringstream    myStream;
        myStream.precision(8);
        myStream.setf(std::ios_base::fixed, std::ios_base::floatfield);
        myStream &lt;&lt; 3.1415926535897932384626433832795;
    const std::wstring ws(myStream.str());
    pDataElement-&gt;setAttribute(L"float", ws.c_str());
    
    // Append 'pDataElement' to 'pRootElement'.
    pRootElement-&gt;appendChild(pDataElement);
 
 
// Create an Element node, then fill in some attributes, add some text,
// then append this to the 'pDataElement' element.
DOMElement * pRow = NULL;
pRow = pDOMDocument-&gt;createElement(L"tow");
 
    // Create some sample data.
    _itow_s(1, wcharBuffer, 128, 10);
    pRow-&gt;setAttribute(L"index", wcharBuffer);
 
    /*
    Create a text node and append this as well. Some people 
    prefer to place their data in the text node
    which is perfectly valid, others prefer to use 
    the attributes. A combination of the two is quite common.
    */
    DOMText* pTextNode = NULL;
    pTextNode = pDOMDocument-&gt;createTextNode(L"Comments and" 
                L" data can also go in text nodes.");
    pRow-&gt;appendChild(pTextNode);
    pDataElement-&gt;appendChild(pRow);
 
 
// Create a new  row (this time putting data and descriptions into different places).
pRow = pDOMDocument-&gt;createElement(L"ConstantPI");
    pRow-&gt;setAttribute(L"description", L"The value of PI");
    pTextNode = pDOMDocument-&gt;createTextNode(L"3.1415");
    pRow-&gt;appendChild(pTextNode);
    pDataElement-&gt;appendChild(pRow);
 
 
// Create a new row.
pRow = pDOMDocument-&gt;createElement(L"UsefulLinks");
    pRow-&gt;setAttribute(L"website", L"http://www.programminggeeksinchrysalis.blogspot.com/");
    pTextNode = pDOMDocument-&gt;createTextNode(L"Blog worth Reading.");
    pRow-&gt;appendChild(pTextNode);
    pDataElement-&gt;appendChild(pRow);
    char* path="c:\\temp\\sample.xml";
    Serialiser_XML_writer(pDOMDocument,path);
 
//Release The Document after the xml file has been written
    pDOMDocument-&gt;release();
    XMLPlatformUtils::Terminate();
    }
 
 


Method XML writer:


/*****************************************
* author: Aniruddha S N
*
* Description: the function serializes the DOM tree 
* and writes it in XML form to the mentioned file.
*
*/
 
#include <iostream>
#include <vector>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/framework/StdOutFormatTarget.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <time.h>
#include <string>
#include <sstream>
using namespace std;
//below macro gives all the required namespaces for Xerces
XERCES_CPP_NAMESPACE_USE
 
void Serialiser_XML_writer(xercesc::DOMDocument* pDOMDocument, char* FullFilePath )
{
DOMImplementation *pImplement = NULL;
DOMLSSerializer *pSerializer = NULL; // @DOMWriter
LocalFileFormatTarget *pTarget = NULL; 
 
//Return the first registered implementation that has the desired features. In this case, we are after
//a DOM implementation that has the LS feature... or Load/Save.
 
pImplement = DOMImplementationRegistry::getDOMImplementation(L"LS");
 
//From the DOMImplementation, create a DOMWriter.
//DOMWriters are used to serialize a DOM tree [back] into an XML document.
 
pSerializer = ((DOMImplementationLS*)pImplement)-&gt;createLSSerializer(); 
DOMLSOutput *pOutput = ((DOMImplementationLS*)pImplement)-&gt;createLSOutput();
DOMConfiguration *pConfiguration = pSerializer-&gt;getDomConfig();
 
// Have a nice output
if (pConfiguration-&gt;canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true))
pConfiguration-&gt;setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); 
pTarget = new LocalFileFormatTarget(FullFilePath);
pOutput-&gt;setByteStream(pTarget);
 
//pSerializer->write(pDOMDocument->getDocumentElement(), pOutput); // missing header "" if used
pSerializer-&gt;write(pDOMDocument, pOutput); 
 
delete pTarget;
pOutput-&gt;release();
pSerializer-&gt;release();
}
 


Output File:


<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<ex:Hello_World xmlns:ex="schemas.example.com/2008/">

  <!--Dates are formatted mm/dd/yy. Don't forget XML is case-sensitive.-->

  <data date="05/02/13" float="3.14159265" integer="65536">
    <tow index="1">Comments and data can also go in text nodes.</tow>
    <ConstantPI description="The value of PI">3.1415</ConstantPI>
    <UsefulLinks website="http://www.programminggeeksinchrysalis.blogspot.com/">Blog worth Reading.</UsefulLinks>
  </data>

</ex:Hello_World>





Sunday, 28 April 2013

SAX Parser In JAVA

The following code demonstrates the use of sax parser in JAVA :

main function wherein you initialise the parser and call for parsing the file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/****************************
 * author: Aniruddha SN
 *
 */
 
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import customHandler.anrSaxHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
 
public class XMLParser
{
    public static void main(String args[])
        {
                try
                {
                //create an input source for parsing
                //u can accept the file path as argument, harcoding for example
                File myfile= new File("c:\\temp\\sample1.xml");
                InputStream inputstream= new FileInputStream(myfile);
                InputStreamReader isr=new InputStreamReader(inputstream);
                InputSource inputsource=new InputSource(isr);
                
                //initialise the sax parser 
                SAXParserFactory saxfact=SAXParserFactory.newInstance();
                SAXParser saxparser=saxfact.newSAXParser();
                
                //call parse funstion  with a custom sax handler object as input
                saxparser.parse(inputsource,new anrSaxHandler());
                
                }
                catch(Exception e)
                {
                        System.out.println(e.getMessage());
                }
        }
}


custom SAX handler to override  the functionality:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*****************************
 * author: Aniruddha S N
 */
package customHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
public class anrSaxHandler extends DefaultHandler
{
    
        //function informs the sax event begining of a new element
        public void startElement(String uri, String localName,String qName, 
            Attributes attributes) throws SAXException {
                
                // u can write ur functionality here
                
                //sample functionality to print the element name and its attributes
                
                System.out.println("Reading element:"+qName+"\n");
                System.out.println("Attributes of the element and their values:\n");
                for(int i=0;i<attributes.getLength();i++)
                {
                        System.out.println(attributes.getLocalName(i)+": "+attributes.getValue(i)+"\n");
                }
                System.out.println("Data:");
        }
        
        //function informs the occurence of sax event end of an element
        public void endElement(String uri, String localName,
                        String qName) throws SAXException {
  
                //planned action on end of element can be added here
                
                //sample functionality forprinting the element name
                
                
                System.out.println("Finished Reading element:"+qName+"\n");
                
        }
        
   //function provides the data within a tag
        public void characters(char ch[], int start, int length) throws SAXException {
                
                
                //sample functionality to store data in a string and print it
                
                
                   String data=new String(ch,start, length);
                   System.out.println(""+data+"\n");
                
                
        }
}


sample file:



Results Of Parsing:

Reading element:catalog
 
Attributes of the element and their values:
 
Data:
 
   
 
Reading element:book
 
Attributes of the element and their values:
 
id: bk101
 
Data:
 
      
 
Reading element:author
 
Attributes of the element and their values:
 
Data:
Gambardella, Matthew
 
Finished Reading element:author
 
 
      
 
Reading element:title
 
Attributes of the element and their values:
 
Data:
XML Developer's Guide
 
Finished Reading element:title
 
 
      
 
Reading element:genre
 
Attributes of the element and their values:
 
Data:
Computer
 
Finished Reading element:genre
 
 
      
 
Reading element:price
 
Attributes of the element and their values:
 
Data:
44.95
 
Finished Reading element:price
 
 
      
 
Reading element:publish_date
 
Attributes of the element and their values:
 
Data:
2000-10-01
 
Finished Reading element:publish_date
 
 
      
 
Reading element:description
 
Attributes of the element and their values:
 
Data:
An in-depth look at creating applications 
      with XML.
 
Finished Reading element:description
 
 
   
 
Finished Reading element:book
 
 
 
 
Finished Reading element:catalog




Thursday, 10 January 2013

Queue Implementation using LinkedList

Queue is a FIFO type data structure ie element which is inserted first can be deleted first or goes out first, the following program gives implementation of queue using linked list:



/*************************************************************
* Author: Aniruddha S N
* 
*/

#include<iostream>

using namespace std;

// structure node
struct node
{
    int info;
    struct node* next;
    struct node* prev;
};


//function declaration
void insertQueue(int ele);
void deleteQueue();
void displayQueue();
void freeQueueMemory();

//Global Variables
node* front = NULL;
node* rear  = NULL;

//main function
int main()
{
    int ch    = 0;
    int ele   = 0;

    while(1)
    {
        cout<<"**************QueueOperations********************\n";
        cout<<"1------->insert an element into queue\n";
        cout<<"2------->display the queue\n";
        cout<<"3------->delete an element from queue\n";
        cout<<"*************************************************\n";
        cout<<"Enter your choice\n";
        cin>>ch;
        //use the switch case to call functions for respective operations
        switch(ch)
        {
        case 1: cout<<"Enter the element to be inserted into the queue\n";
                cin>>ele;
                insertQueue(ele);
                break;
        case 2: displayQueue();
                break;
        case 3: deleteQueue();
                break;
        default:freeQueueMemory();
                exit(0);
        }
    }
}

void insertQueue(int ele)
{
    node* temp;
    if(front == NULL)
    {
     temp= new node();
     temp->info=ele;
     temp->next=NULL;
     temp->prev=NULL;
     front = temp;
     rear  = temp;
    }
    else
    {
        temp=new node();
        temp->info=ele;
        temp->next=NULL;
        rear->next=temp;
        temp->prev=rear;
        rear=temp;
    }
}

//function to delete an element from queue
void deleteQueue()
{
    node* temp;
    if(front == NULL || rear == NULL)
      cout<<"Queue is empty\n";

  else
  {
      //delete an element from front
      temp=front->next;
      if(front->next != NULL)
      temp->prev=NULL;
      front->next=NULL;
      delete front;

      //make front point to the next element
      front = temp;
    }
}
void displayQueue()
{
    node*temp;
    temp=front;
    cout<<"\nQueue Elements from front:\n";
    while(temp != NULL)
    {
        cout<<temp->info<<"\n";
        temp=temp->next;
    }
}
void freeQueueMemory()
{
    node* temp;
    node* prev = NULL;
    temp=front;
    if(front == NULL || rear == NULL)
        return;
//traverse through the queue and delete the memory assigned to all the nodes
    while(temp->next != NULL)
    {
        prev=temp;
        temp=temp->next;
        temp->prev=NULL;
        prev->next=NULL;
        prev->prev=NULL;
        delete prev;
        prev=NULL;
    }
// delete the memory of last node
    temp->prev=NULL;
    temp->next=NULL;
    delete temp;
    temp = NULL;
}