vb6 code sample

Document Sample
vb6 code sample Powered By Docstoc
					JAVA Sample Implementation

[Note the Elections Information Project has been since re-branded as “Voting
Information Project” (VIP). Also, this document refers to version 1.0 of the spec. While
the spec has since evolved, the principles in this document are the same.]

Sample Java Pseudo Code Implementation for generating EIP feeds.
This document presents code sample for generating XML in JAVA. For most instances,
the XML will be generated with data extracted from a database. To keep this simple, we
will generate XML from a list preloaded with hard code data. The output will be eip.xml
file with the following content. Below example uses open source Xerces parser to
generate XML document. Xerces provides XML generation and parsing utility.

Sample Output XML

<?xml version="1.0" encoding="UTF-8"?>
<eip_object xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="election.xsd" schemaVersion="x.x">
      <election id="12345">
        <date>05-09-2007</date>
        <statewide>yes</statewide>
        <state_id>49</state_id>
        <election_type>Federal</election_type>
        <results_url>http://elections.results.org</results_url>
        <registration_info>To register for this
election</registration_info>
        <absentee_ballot_info>To request an absentee
ballot</absentee_ballot_info>
        <polling_hours>7am-8pm</polling_hours>
      </election>
      <state id="1">
        <name>Alabama</name>
        <elections_url>http://www.alabamaelections.org</elections_url>
        <rules_url>http://electionrules.org</rules_url>
      </state>
        ...
        ...
        ...

</eip_object>

The steps involved in XML generation are:

    1. Load data from a database repository. For simplicity, we will just use hard-coded
       values.
    2. Get an instance of Document object using document builder factory
    3. Create the root element "eip_object"
    4. For each item in the list create a Election, State, elements.
    5. Serialize DOM to FileOutputStream to generate the xml file "eip.xml".
Let's go over each of the above steps in more detail:

1) Load Data
         /**
          * Add a list of objects (Election, States, etc.) to the list
          * Typically you might populate the list from a database
          */
         private void loadData(){

                   // Add a Election object to myData
                   myData.add(new Election(
                               "12345",           // id
                               "05-09-2007",      // date
                               "yes",             // statewide
                               "49",              // state id
                               "Federal",         // election type
                               "http://elections.results.org", //results
url
                                   "To register for this election",
//registration info
                                   "To request an absentee ballot", //absentee
ballot info
                                   "7am-8pm"));           //polling_hours

        // Add a State object to myData
               myData.add(new State(
                            "1",                                            // id
                            "Alabama",                                      //
name of the state
                            "http://www.alabamaelections.org",              //
elections url
                            "http://electionrules.org"));                    //
rules url

         }

2) Getting an instance of DOM.

        /**
         * Using JAXP in implementation independent manner create a
document object
         * using which we create a xml tree in memory
         */
        private void createDocument() {

               //get an instance of factory
               DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
               try {
               //get an instance of builder
               DocumentBuilder db = dbf.newDocumentBuilder();
                 //create an instance of DOM
                 dom = db.newDocument();

                 }catch(ParserConfigurationException pce) {
                         //dump it
                         System.out.println("Error while trying to
instantiate
                                                  DocumentBuilder " +
pce);
                        System.exit(1);
                 }
        }

3) Create the root element eip_object

   /**
    * The real horse which creates the XML structure
    */
        private void createDOMTree(){

                 //create the root element
                 Element rootElement = dom.createElement("eip_object");
                 rootElement.setAttribute("xmlns:xsi",
                                          "http://www.w3.org/2001/XMLSche
ma-instance");
                 rootElement.setAttribute("xsi:noNamespaceSchemaLocation",
                                              "election.xsd");
                 dom.appendChild(rootElement);

                 //No enhanced for
                 Iterator it = myData.iterator();

               while(it.hasNext()) {
                       Election e = (Election)it.next();
                       //For each Election object create an element and
                        //attach it to root element
                       Element electionElement =
createElectionElement(e);
                       rootElement.appendChild(electionElement);

                        State st = (State)it.next();
                        //For each State object create an element and
                         //attach it to root element
                        Element stateElement = createStateElement(st);
                        rootElement.appendChild(stateElement);


                // Similarly add all other specs elements to root
object "eip_object"
               }
        }

4) Creating a election and state element functions

        /**
         * Helper method which creates a XML element <election>
         * @param The election for which we need to create an xml
representation
         * @return XML element representing a election
         */
        private Element createElectionElement(Election e){

          Element electionElement = dom.createElement("Election");
          electionElement.setAttribute("id", e.getId());

          //create date element and add it to Election element
          Element dateElement = dom.createElement("date");
          Text dateText = dom.createTextNode(e.getDate());
          dateElement.appendChild(dateText);
          electionElement.appendChild(dateElement);

          //create statewide element and add it to Election element
          Element stateWideElement = dom.createElement("statewide");
          Text stateWideText = dom.createTextNode(e.getStatewide());
          stateWideElement.appendChild(stateWideText);
          electionElement.appendChild(stateWideElement);

           //create state id element and add it to Election element
           Element stateidElement = dom.createElement("stateid");
           Text stateidText = dom.createTextNode(e.getStateId());
           stateidElement.appendChild(stateidText);
           electionElement.appendChild(stateidElement);

         //create election type element and add it to Election element
         Element electionTypeElement =
dom.createElement("electiontype");
         Text electionTypeText =
dom.createTextNode(e.getElectionType());
         electionTypeElement.appendChild(electionTypeText);
         electionElement.appendChild(electionTypeElement);

           //create results url element and add it to Election element
           Element resultsUrlElement = dom.createElement("results_url");
           Text resultsUrlText = dom.createTextNode(e.getResultsUrl());
           resultsUrlElement.appendChild(resultsUrlText);
           electionElement.appendChild(resultsUrlElement);

           //create registration info element and add it to Election
element
         Element regInfoElement =
dom.createElement("registration_info");
         Text regInfoText =
dom.createTextNode(e.getRegistrationInfo());
         regInfoElement.appendChild(regInfoText);
         electionElement.appendChild(regInfoElement);

           //create absentee ballot element and add it to Election
element
         Element absenteeBallotInfoElement =
dom.createElement("absentee_ballot_info");
         Text absenteeBallotInfoText =
dom.createTextNode(e.getAbsenteeBallotInfo());
         absenteeBallotInfoElement.appendChild(absenteeBallotInfoText);
         electionElement.appendChild(absenteeBallotInfoElement);

         //create Polling Hours element and add it to Election element
         Element pollingHoursElement =
dom.createElement("polling_hours");
         Text pollingHoursText =
dom.createTextNode(e.getPollingHours());
         pollingHoursElement.appendChild(pollingHoursText);
         electionElement.appendChild(pollingHoursElement);

          return electionElement;
        }
       /**
          * Helper method which creates a XML element <state>
          * @param The election for which we need to create an xml
representation
          * @return XML element representing a election
          */
        private Element createStateElement(State st){

       Element stateElement = dom.createElement("state");
       stateElement.setAttribute("id", st.getId());

       //create name element and add it to State element
       Element nameElement = dom.createElement("name");
       Text nameText = dom.createTextNode(st.getName());
       nameElement.appendChild(nameText);
       stateElement.appendChild(nameElement);

        //create elections url element and add it to Election element
        Element electionsUrlElement =
dom.createElement("elections_url");
        Text electionsUrlText =
dom.createTextNode(st.getElectionsUrl());
        electionsUrlElement.appendChild(electionsUrlText);
        stateElement.appendChild(electionsUrlElement);

       //create elections url element and add it to Election element
       Element rulesUrlElement = dom.createElement("rules_url");
       Text rulesUrlText = dom.createTextNode(st.getRulesUrl());
       rulesUrlElement.appendChild(rulesUrlText);
       stateElement.appendChild(rulesUrlElement);

       return stateElement;
       }




5) Serialize DOM to FileOutputStream to generate the xml file "eip.xml".

       /**
        * This method uses Xerces specific classes
        * prints the XML document to file.
        */
       private void printToFile(){
                try
                {
                       //print
                       OutputFormat format = new OutputFormat(dom);
                       format.setIndenting(true);

                       //to generate output to console use this
serializer
                       //XMLSerializer serializer = new
XMLSerializer(System.out,

     format);

                       //to generate a file output use fileoutputstream
instead
                        //of system.out
                       XMLSerializer serializer = new XMLSerializer(
                       new FileOutputStream(new
File("c:\\temp\\eip.xml")), format);

                       serializer.serialize(dom);

                } catch(IOException ie) {
                    ie.printStackTrace();
                }
          }

Complete code example is provided in files section. The code example
should be
used as a reference only. We have tried our best to ensure accuracy,
but if you
find any errors, please let us know. Please feel free to contact us if
you have
any other questions.
Visual Basic Sample Implementation

                                                           document shows how to
Sample VB Pseudo Code Implementation for generating EIP feeds. This
create an XML document using VB 6.0. The below code is just a pseudo code (and not
complete implementation) and is meant to provide guidance to VB developers on how to
generate XML document. The document assumes you are already familiar with coding in
Visual Basic (VB). The document also assumes you already have MSXML 3.0 (or
higher) library. If not, download it from MSDN site.

The tutorial uses the W3C DOM (Document Object Model) which allows the user to
navigate and manipulate the XML document through its various methods and properties.
Before you start using MSXML, you should add a reference to the MSXML library. This
is typically done by accessing the References item when you click on Project in the main
menu as shown. There may be several versions on your machine (there are about five on
this machine) depending on several factors, but you can identify it in the References
window if you have it on your machine.




Creating an XML Document using VB 6.0



This section will describe the steps you need to take in creating a document such as the
one shown in the next paragraph.

<?xml version="1.0"?> <!--Processing Instruction-->
<eip_object> <!--Root object-->
      <election id="12345">     <!--Election node-->
        <date>05-09-2007</date> <!--Child of election node -->
        <statewide>yes</statewide>
        <state_id>49</state_id>
        <election_type>Federal</election_type>
        <results_url>http://elections.results.org</results_url>
        <registration_info>To register for this
election</registration_info>
        <absentee_ballot_info>To request an absentee
ballot</absentee_ballot_info>
        <polling_hours>7am-8pm</polling_hours>
      </election>
      <state id="1">            <!--State node-->
        <name>Alabama</name>    <!--Child of State node -->
        <elections_url>http://www.alabamaelections.org</elections_url>
        <rules_url>http://electionrules.org</rules_url>
      </state>
        ...
        ...
        ...

</eip_object>




Creating the root node, child node and attributes

The XML document is built using DomDocument class - line by line. Every XML
document has a processing instruction at the very top of the document. The document
must have a root element. The code listing shown allows you to create an XML document
with the root node "eip_object", the element "election" which is a child of the root and
"date" element which is a child of "election" element. The values below are hard-coded
for demonstration purposes. Typically, these values will be extracted from database
tables.

Private Sub Command1_Click()
Dim xmldoc As DOMDocument30
Dim ProcInstr As IXMLDOMProcessingInstruction
Dim rootElement As IXMLDOMElement
Dim aElement As IXMLDOMElement
Dim cElement As IXMLDOMElement
Dim dElement As IXMLDOMElement
Dim att As IXMLDOMAttribute
'Creating DOM Document object
Set xmldoc = New DOMDocument30
'this adds the processing instruction
'the first line in an XML document
Set ProcInstr = xmldoc.createProcessingInstruction("xml",
"version=""1.0""")
xmldoc.appendChild ProcInstr
'Create the root element
Set rootElement = xmldoc.createElement("eip_object")
Set xmldoc.documentElement = rootElement
'Create the node election
Set electionElement = xmldoc.createElement("election")
'add the election node to the root
rootElement.appendChild electionElement
'create a child element, 'date' for the election
Set dateElement = xmldoc.createElement("date")
'add a value for this node, '05-09-2007'
dateElement.nodeTypedValue = "05-09-2007"
'dateElement is child of electionElement
'add the dateElement as a child of electionElement
electionElement.appendChild dateElement

'append another child to the 'election' element
'-------------
Set statewideElement = xmldoc.createElement("statewideElement")
statewideElement.nodeTypedValue = "Yes"
electionElement.appendChild statewideElement

....'---- similarly add all other child elements to election node ---

'-------adding attributes---
'---create an attribute using the createAttribute() method
'---at the same time set its name
Set att = xmldoc.createAttribute("id")
'---set the attributes 'text' property
att.Text = "12345"
'--for the electionElement, which is 'election' set a named
'---attribute, it's name is att
electionElement.Attributes.setNamedItem att
'----------------------
'Saving the xml document to c:eip.xml
xmldoc.save "c:eip.xml"

' end of program
End Sub