Pages

Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Thursday, June 5, 2014

getXMLString from an XML Node Object

Following is a simple function that would let you obtain the XML contents of a XML node in a string format. The packages that had been imported into the class are listed as follows. I hope these are available as a free download

 

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

 

public static String getXMLString(Node xmlNode){

              String xmlString = null;

              xmlString="<";

              xmlString+=xmlNode.getNodeName();

             

              NamedNodeMap attributes=xmlNode.getAttributes();

              int noOfAttributes=attributes.getLength();

              int itr=0;

             

              for (itr=0;itr<noOfAttributes;itr++)     {

                     Node attributeNode=attributes.item(itr);

                     xmlString+=" "+ attributeNode.getNodeName() + "=" + attributeNode.getNodeValue();

              }

              xmlString+=">";

             

              NodeList childNodes=xmlNode.getChildNodes();

              int noOfChildNodes=childNodes.getLength();

             

              if (noOfChildNodes==0)     {

                     xmlString+=xmlNode.getNodeValue();

              }      else   {

                     int childNodeItr=0;

                     for (childNodeItr=0;childNodeItr<noOfChildNodes;childNodeItr++)      {

                           xmlString += getXMLString(childNodes.item(childNodeItr));

                     }

              }

             

              xmlString+="</"+xmlNode.getNodeName()+">";

             

              return xmlString;

       }

 

 

Creating an XML Document node from XML string

Following method helps you convert XML String into a XML Document Object

 

import java.io.ByteArrayInputStream;

import java.io.InputStream;

 

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

 

import org.w3c.dom.Document;

      

public Document getXMLDoc(String xmlString) {

       InputStream is = new ByteArrayInputStream(xmlString.getBytes());

       DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

       DocumentBuilder dBuilder = null;

       Document doc = null;

       try {

              dBuilder = dbFactory.newDocumentBuilder();

              doc = dBuilder.parse(is);

       } catch (Exception e) {

              // TODO Auto-generated catch block

              // logger.error("Parsing exception iha xml traversal");

       }

      

       return doc;

}

      

You can use the doc object as follows

 

doc.getElementsByTagName(tagName)

 

 

Monday, June 2, 2014

Creating a jar file through eclipse

Its rather simple and straight forward to create a jar file using eclipse. I am employing an ant build file to do this stuff.

 

Create a project and add a class to it as follows

package com.self.jarTest;

 

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello World");

    }

}

 

Now create a build.xml file in the root of your project folder with the following content

<project>

 

    <target name="clean">

        <delete dir="build"/>

    </target>

 

    <target name="compile">

        <mkdir dir="build/classes"/>

        <javac srcdir="src" destdir="build/classes"/>

    </target>

 

    <target name="jar">

        <mkdir dir="build/jar"/>

        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">

            <manifest>

                <attribute name="Main-Class" value="com.self.jarTest.HelloWorld"/>

            </manifest>

        </jar>

    </target>

 

    <target name="run">

        <java jar="build/jar/HelloWorld.jar" fork="true"/>

    </target>

 

</project>

 

Now right click on the build.xml and click on “Run As -> 3.Ant Build -> Clean, Compile, run, jar -> Run“

 

That’s it you got your jar file J

 

Wednesday, May 28, 2014

XML String to JSON conversion in javascript

 

I found this nice simple jquery plugin that helps convert xml string into JSON object directly converts xml string into json object in javascript. Following is a simple html file that I used to test my way through with this plugin. So my motive is to get a message box in the browser saying “Hello World” through the following file. Hope I don’t have to speak much about this file as its very plain and simple

 

----------------------------------------------------------------------------------------------------------------------------

<html>

                <head>

                                <script type='text/javascript' src='jquery.js'></script>

                                <script type='text/javascript' src='jquery.xml2json.js'></script>                               

                                <script type='text/javascript'>

                                                function xmlToJsonTest()             {

                                                                var xml = '<xml><message>Hello world</message></xml>';

                                                                var json = $.xml2json(xml);

                                                                alert(json.message);

                                                }

                                </script>

                </head>

 

                <body onload='xmlToJsonTest()'>XML To JSON Test</body>

 

</html>

----------------------------------------------------------------------------------------------------------------------------

 

You can find this xml to json convertor jquery plugin in http://www.fyneworks.com/jquery/xml-to-json/ .

 

You can go through the site for examples and if you would like to skip the hard part here is the direct download link for the same site for the plugin http://jquery-xml2json-plugin.googlecode.com/svn/trunk/jquery.xml2json.js

 

Hope this helps

 

 

Thursday, August 1, 2013

Android Hello World Part 2

This is a continuation from the previous post.

To respond to the button's on-click event, open theactivity_main.xml layout file and add theandroid:onClick attribute to the <Button> element:

<Button
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:text="@string/button_send"
   
android:onClick="sendMessage" />

The android:onClick attribute’s value, "sendMessage", is the name of a method in your activity that the system calls when the user clicks the button.

Open the MainActivity class (located in the project's src/ directory) and add the corresponding method:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
   
// Do something in response to button
}

This requires that you import the View class:

import android.view.View;

Build an Intent


An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.

Inside the sendMessage() method, create an Intent to start an activity called DisplayMessageActivity:

Intent intent = new Intent(this, DisplayMessageActivity.class);

An Intent can carry a collection of various data types as key-value pairs called extras. The putExtra()method takes the key name in the first parameter and the value in the second parameter.

 

An intent not only allows you to start another activity, but it can carry a bundle of data to the activity as well. Inside thesendMessage() method, use findViewById() to get theEditText element and add its text value to the intent:

Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent
.putExtra(EXTRA_MESSAGE, message);

Note: You now need import statements forandroid.content.Intent and android.widget.EditText.

Start the Second Activity


To start an activity, call startActivity() and pass it your Intent. The system receives this call and starts an instance of the Activity specified by the Intent.

With this new code, the complete sendMessage() method that's invoked by the Send button now looks like this:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

To create a new activity using Eclipse:

1.    Click New  in the toolbar.

2.    In the window that appears, open theAndroid folder and select Android Activity. Click Next.

3.    Select BlankActivity and click Next.

4.    Fill in the activity details:

o    Project: MyFirstApp

o    Activity Name: DisplayMessageActivity

o    Layout Name: activity_display_message

o    Title: My Message

o    Hierarchial Parent: com.example.myfirstapp.MainActivity

o    Navigation Type: None

Click Finish.

If you're using a different IDE or the command line tools, create a new file namedDisplayMessageActivity.java in the project's src/ directory, next to the original MainActivity.java file.

Open the DisplayMessageActivity.java file. If you used Eclipse to create this activity:

·         The class already includes an implementation of the required onCreate() method.

·         There's also an implementation of the onCreateOptionsMenu() method, but you won't need it for this app so you can remove it.

·         There's also an implementation of onOptionsItemSelected() which handles the behavior for the action bar's Up behavior. Keep this one the way it is.

Because the ActionBar APIs are available only on HONEYCOMB (API level 11) and higher, you must add a condition around the getActionBar() method to check the current platform version. Additionally, you must add the @SuppressLint("NewApi") tag to the onCreate() method to avoid lint errors.

The DisplayMessageActivity class should now look like this:

public class DisplayMessageActivity extends Activity {

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView
(R.layout.activity_display_message);

       
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
       
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
           
// Show the Up button in the action bar.
            getActionBar
().setDisplayHomeAsUpEnabled(true);
       
}
   
}

   
@Override
   
public boolean onOptionsItemSelected(MenuItem item) {
       
switch (item.getItemId()) {
       
case android.R.id.home:
           
NavUtils.navigateUpFromSameTask(this);
           
return true;
       
}
       
return super.onOptionsItemSelected(item);
   
}
}

Add the title string

If you used Eclipse, you can skip to the next section, because the template provides the title string for the new activity.

If you're using an IDE other than Eclipse, add the new activity's title to the strings.xml file:

<resources>
    ...
    <string name="title_activity_display_message">My Message</string>
</resources>

Add it to the manifest

All activities must be declared in your manifest file, AndroidManifest.xml, using an <activity> element.

When you use the Eclipse tools to create the activity, it creates a default entry. If you're using a different IDE, you need to add the manifest entry yourself. It should look like this:

<application ... >
    ...
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Receive the Intent


Every Activity is invoked by an Intent, regardless of how the user navigated there. You can get the Intentthat started your activity by calling getIntent() and retrieve the data contained within it.

In the DisplayMessageActivity class’s onCreate() method, get the intent and extract the message delivered by MainActivity:

Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

Display the Message


To show the message on the screen, create a TextView widget and set the text using setText(). Then add theTextView as the root view of the activity’s layout by passing it to setContentView().

The complete onCreate() method for DisplayMessageActivity now looks like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 
    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
 
    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);
 
    // Set the text view as the activity layout
    setContentView(textView);
}

 

The final set of code that you would have arrived could be the following

 

 

 

 

 

This enabled me to do the following J