Header Ad

Sunday, April 1, 2012

Concatenation of String array to String

This program will help to concatenate String array to a simple string with a delimiter( if require).

public class StrArrtoStr {

public static void main(String[] args) {
String weeks_days[] = new String[7];
weeks_days[0] = "Sunday";
weeks_days[1] = "Monday";
weeks_days[2] = "Tuesday";
weeks_days[3] = "Wednesday";
weeks_days[4] = "Thursday";
weeks_days[5] = "Friday";
weeks_days[6] = "Saturday";
StringBuffer finalString = new StringBuffer();

if (weeks_days.length > 0) {
finalString.append(weeks_days[0]);
for (int i = 1; i < weeks_days.length; i++) {
finalString.append(",");
finalString.append(weeks_days[i]);
}
}

System.out.println("Concatenation of String array to String:::"
+ finalString.toString());

}

}

In the above example, we have String array of length 7 having items(weeks). We need to concatenate all these into a one string.

The above program will provide a final output which is as follows:
Concatenation of String array to String::: Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

Tuesday, June 15, 2010

Parsing XML string or content using java code

The following program is an example for parsing the XML string using code.

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
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;

public class XMLParse {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "A"
        + "";

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("employee");

    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);

      NodeList name = element.getElementsByTagName("name");
      Element line = (Element) name.item(0);
      System.out.println("Name: " + getCharacterDataFromElement(line));

      NodeList title = element.getElementsByTagName("title");
      line = (Element) title.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }

  }

  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
    }
    return "";
  }
}