How to get all of elements from String(xml) with Parser<ObjectNode> - java

I get soap xml response and convert to String. String (xml) Example:
<Details>
<row>
<item>
<name>account</name>
<value>45687447</value>
</item>
<item>
<name>number</name>
<value>896541</value>
</item>
</row>
<row>
<item>
<name>account</name>
<value>2669874</value>
</item>
<item>
<name>number</name>
<value>063641</value>
</item>
</row>
</Details>
Now i parsing the String like this:
public ObjectNode ParseXml(String xml) {
Parsing parsing = ParsingFactory.getInstance().create();
Document document = parsing.xml().document(xml);
Parser<ObjectNode> parser = parsing.obj("//Details")
.attribute("row", parsing.obj("//row")
.attribute("account", "//item[name/text() = 'account']/value")
.attribute("number", "//item[name/text() = 'number']/value")).build();
ObjectNode result = parser.apply(document);
return result;
}
But problem is the, i take only one row, like this:
{
"row": {
"account": "2669874",
"number": "063641",
}
}
If i have 10 rows, but i get only one row. How i can get all rows?

I'm parsing from .xml file which you can easily change and have log on this files too.
package java_testiranja;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* #author blac
*/
public class Java_testiranja {
/**
* #param xml
* #param args the command line arguments
*/
private List<Employee> myEmpls = new ArrayList<Employee>();
public static void main(String[] args) throws IOException, ParserConfigurationException {
Java_testiranja domParser = new Java_testiranja();
domParser.parseXmlFile();
}
private void parseXmlFile() throws IOException, ParserConfigurationException {
// get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
Document dom = db.parse("employee.xml");
parseDocument(dom);
printData();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument(Document dom) {
// get the root element
Element docEle = dom.getDocumentElement();
// get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("item");
int stevilor = nl.getLength();
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
// get the employee element
Element el = (Element) nl.item(i);
// get the Employee object
Employee e = getEmployee(el);
// add it to list
myEmpls.add(e);
}
}
}
/**
* I take an employee element and read the values in, create an Employee object and return it
*/
private Employee getEmployee(Element empEl) {
// for each <employee> element get text or int values of
// name ,id, age and name
String name = getTextValue(empEl, "name");
int id = getIntValue(empEl, "value");
//int age = getIntValue(empEl, "Age");
//String type = empEl.getAttribute("type");
// Create a new Employee with the value read from the xml nodes
Employee e = new Employee(name, id);
return e;
}
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
private int getIntValue(Element ele, String tagName) {
// in production application you would catch the exception
return Integer.parseInt(getTextValue(ele, tagName));
}
private void printData() {
Iterator<Employee> it = myEmpls.iterator();
while (it.hasNext()) {
System.out.println("{" + "\n" + "\"row\": {");
System.out.println(" "+it.next().toString());
System.out.println(" "+it.next().toString());
System.out.println(" }" + "\n" + "}");
}
}
}
And the Employee class is like:
package java_testiranja;
/**
*
* #author blac
*/
public class Employee {
private String name;
private int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "\""+name+"\": " + "\""+id+"\""+",";
}
}
I tried your .xml file and get the result:
{
"row": {
"account": "45687447",
"number": "896541",
}
}
{
"row": {
"account": "2669874",
"number": "63641",
}
}
I just saved .xml file as Employee.xml and called it. You can simply save this results...
Regards,
Blaz

Related

Write excel data into List

I created below class with getter and setter.
import java.util.List;
public class DMNDetails {
private List<String> inputParam;
private List<String> outputParam;
public List<String> getInputParam() {
return inputParam;
}
public void setInputParam(List<String> inputParam) {
this.inputParam = inputParam;
}
public List<String> getOutputParam() {
return outputParam;
}
public void setOutputParam(List<String> outputParam) {
this.outputParam = outputParam;
}
#Override
public String toString() {
return ("Inputname: "+ getInputParam()+
" Outputname: "+ getOutputParam());
}
}
Extracting input and output variables from XML and return using List.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ExtractingValues {
public DMNDetails Param() {
List<String> inputval = new ArrayList<String>();
DMNDetails dtls = new DMNDetails();
String variables;
// String dataType;
try {
File file = new File("C:/test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
// System.out.println("Root element: "+ doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("inputExpression");
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
// System.out.println("\nNode Name :" + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element tElement = (Element)node;
variables = tElement.getElementsByTagName("text").item(0).getTextContent();
// dataType = tElement.getAttribute("typeRef");
// System.out.println("Variable: "+ variables);
// System.out.println("Type: "+ dataType);
switch(i) {
case 0:
inputval.add(variables);
// System.out.println("Input1: "+dtls1.getInput1());
break;
case 1:
inputval.add(variables);
// System.out.println("Input2: "+dtls2.getInput2());
break;
case 2:
inputval.add(variables);
// System.out.println("Input3: "+dtls3.getInput3());
break;
default:
System.out.println("Error");
}
}
}
}
catch (Exception e) {
System.out.println(e);
}
dtls.setInputParam(inputval);
/*** OutputVariable Section ***/
List<String> outputval = new ArrayList<String>();
String variablesout;
// String dataType;
try {
File file = new File("C:/Jira_task/Sprint_17/Business.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
// System.out.println("Root element: "+ doc.getDocumentElement().getNodeName());
NodeList nodeList2 = doc.getElementsByTagName("output");
for (int i = 0; i < nodeList2.getLength(); ++i) {
Node node2 = nodeList2.item(i);
// System.out.println("\nNode Name :" + node2.getNodeName());
if (node2.getNodeType() == Node.ELEMENT_NODE) {
Element tElement = (Element)node2;
variablesout = tElement.getAttribute("name");
// dataType = tElement.getAttribute("typeRef");
// System.out.println("Variable: "+ variables);
// System.out.println("Type: "+ dataType);
switch(i) {
case 0:
outputval.add(variablesout);
// System.out.println("Output1: "+dtls1.getOutput1());
break;
case 1:
outputval.add(variablesout);
// System.out.println("Output2: "+dtls2.getOutput2());
break;
case 2:
outputval.add(variablesout);
// System.out.println("Output3: "+dtls3.getOutput3());
break;
default:
System.out.println("Error");
}
}
}
}
catch (Exception e) {
System.out.println(e);
}
dtls.setOutputParam(outputval);
return dtls;
}
}
Here we are get data from "TestCase.xlsx" excel and store in data list and return. My expectation are written inside commented block inside.
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelTestCase2 {
public static List<DMNRow> getdata() throws IOException {
List<DMNRow> data = new ArrayList<>();
// Reading file from local directory
FileInputStream file = new FileInputStream("C:\\TestCase.xlsx");
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook XS = new XSSFWorkbook(file);
int numberofsheets = XS.getNumberOfSheets();
for (int i = 0; i < numberofsheets; i++) {
if (XS.getSheetName(i).equalsIgnoreCase("Sheet1")) {
XSSFSheet XSS = XS.getSheetAt(i);
Iterator<Row> r = XSS.iterator();
/* Here input and output variables are hardcode, but cannot able to hardcode value here, because each xml file contain
n number of input and output. So according to n number of variables we need to extract data from excel and store data
in "data". Datatype also change for each variables.
String cr;
long lc;
String arn;
DMNRow DMNRow;
while (r.hasNext()) {
Row row = r.next();
if (row.getRowNum() == 0) {
continue;
}
cr = row.getCell(0).getStringCellValue();
lc = (long) row.getCell(1).getNumericCellValue();
DataFormatter formatter = new DataFormatter();
arn = formatter.formatCellValue(row.getCell(2));
DMNRow = new DMNRow(cr, lc, arn);
data.add(DMNRow);
*/
}
}
}
// Closing file output streams
XS.close();
file.close();
return data;
}
}
After data from excel store and return to another method to compare data with DMN engine and write status in same excel in Result column.
Can anyone please guide how to store data from excel into list to use by another method for compare.

XML Parsing for getting error values while logging in

Below is my xml and java files, when I'm trying to find the error tag value I'm getting the response as
<?xml version="1.0" encoding="UTF-8" ?>
<Error>Invalid User Id/Password. Please try again</Error>
This is my XML
<?xml version="1.0" encoding="UTF-8" ?>
<MENU-ITEMS>
<project>XYX</project>
<project_name>XYZ DEMO TESTING</project_name>
<curr_stu_id>ABC-2222</curr_stu_id>
<curr_stu_name>P.E. Joseph</curr_stu_name>
</MENU-ITEMS>
This is my Java FileJava File :-
public void onResponse(String response)
{
Log.d(TAG, "Login response: " + response);
if (response.contains("<Error>"))
{
String[] responseLines = response.split("\n");
String message = responseLines[2].replace("<Error>","").replace("</Error>","");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
else
{
startActivity(new Intent(MainActivity.this, Welcome.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("response",response)
.putExtra("userName", username.getText().toString()));
}
// I want only the tag value to appear when I am logging in, please help me. I do not want to use
String[] responseLines = response.split("\n");
String message = responseLines[2].replace("<Error>","").replace("</Error>","");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
Add a class XMLParser :
package com.yourpackagename;
import android.util.Log;
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;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML DOM element
* #param xml string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue(Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param item Element
* #param str String
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
/**
* Getting first value from xml
* #param xml String
* #param tag String
* */
public String getFirstValueFromXml(String xml, String tag){
Document doc = getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(tag);
Node node = nl.item(0) ;
String firstValue = getElementValue(node) ;
return firstValue ;
}
}
Then , in your method onResponse() :
public void onResponse(String response) {
XMLParser xmlParser = new XMLParser() ;
String message = xmlParser.getFirstValueFromXml(xml,"Error") ;
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}

Java Pipes Synchronization

I'm working on this program which is supposed to deserialize objects from an XML using the first thread, stream it through pipes to the second thread, which will then sort it and output the results.
The thing is I get exceptions when running it, saying both read and write ends are dead.
When I try to debug though, it works fine, which makes me think it's because of faulty synchronization. Confusing, since I thought the pipes were supposed to handle that aspect. Can anyone help me figure out what I'm doing wrong and point me in the right direction ?
Here's the code for the runnable:
(the relevant parts are near the end)
package domAPI;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ParserRunnable implements Runnable {
List<Employee> myEmpls;
Document dom;
PipedInputStream pin;
PipedOutputStream pout;
ObjectInputStream in;
ObjectOutputStream out;
int threadNr;
// private final Object sending = new Object();
// private final Object receiving = new Object();
public ParserRunnable(){
myEmpls = new ArrayList<Employee>();
}
public ParserRunnable(PipedOutputStream ws, int threadNr){
myEmpls = new ArrayList<Employee>();
pout = ws;
try {
out = new ObjectOutputStream(pout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.threadNr = threadNr;
}
public ParserRunnable(PipedInputStream rs, int ThreadNr){
myEmpls = new ArrayList<Employee>();
pin = rs;
try {
in = new ObjectInputStream(pin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.threadNr = threadNr;
}
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse("persons.xml");
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument(){
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of <employee> elements
NodeList nl = docEle.getElementsByTagName("Employee");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the employee element
Element el = (Element)nl.item(i);
//get the Employee object
Employee e = getEmployee(el);
//add it to list
myEmpls.add(e);
}
}
}
/**
* I take an employee element and read the values in, create
* an Employee object and return it
* #param empEl
* #return
*/
private Employee getEmployee(Element empEl) {
//for each <employee> element get text or int values of
//name ,id, age and name
String name = getTextValue(empEl,"Name");
int id = getIntValue(empEl,"Id");
int age = getIntValue(empEl,"Age");
String type = empEl.getAttribute("type");
//Create a new Employee with the value read from the xml nodes
Employee e = new Employee(name,id,age,type);
return e;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <employee><name>John</name></employee> xml snippet if
* the Element points to employee node and tagName is name I will return John
* #param ele
* #param tagName
* #return
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
* #param ele
* #param tagName
* #return
*/
private int getIntValue(Element ele, String tagName) {
//in production application you would catch the exception
return Integer.parseInt(getTextValue(ele,tagName));
}
/**
* Iterate through the list and print the
* content to console
*/
private void printData(){
System.out.println("No of Employees '" + myEmpls.size() + "'.");
Iterator<Employee> it = myEmpls.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
private void sortByAge(){
Collections.sort(myEmpls);
}
public void run() {
if (out != null){
parseXmlFile();
parseDocument();
writeToStream();
}
if (in != null){
readStream();
sortByAge();
printData();
}
// since i'm using the same class for both the producer and consumer thread
// here, the code above functions as kind of a switch between these 2
// modes of operation, by checking which pipe is initialized.
}
public void writeToStream(){
try{
out.writeObject(myEmpls);
out.flush();
out.close();
pout.flush();
pout.close();
}catch (Exception e) {
System.out.println("ErrorWS:" + e);
}
}
public void readStream(){
try{
myEmpls = (List<Employee>) in.readObject();
in.close();
pin.close();
}catch (Exception e) {
System.out.println("ErrorRS:" + e);
}
}
}
Here's the runner code :
package domAPI;
import java.io.*;
public class Launcher {
public static void main(String[] args){
Thread t1,t2;
try{
PipedOutputStream pos1 = new PipedOutputStream();
PipedInputStream pis2 = new PipedInputStream(pos1);
t1 = new Thread(new ParserRunnable(pos1,1));
t2 = new Thread(new ParserRunnable(pis2,1));
t1.start();
t2.start();
}catch (Exception e) {
System.out.println("Error:" + e);
}
}
}
My code might be pretty tricky to understand. Feel free to bombard me with questions, I'll be available. Also, most of the XML parsing code is originated from here : http://totheriver.com/learn/xml/xmltutorial.html#2
I'll just leave the XML here as well, if need be:
<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
<Employee type="permanent">
<Name>Seagull</Name>
<Id>3674</Id>
<Age>34</Age>
</Employee>
<Employee type="contract">
<Name>Robin</Name>
<Id>3675</Id>
<Age>25</Age>
</Employee>
<Employee type="permanent">
<Name>Crow</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Personnel>
The exception I get :
ErrorRS:java.io.IOException: Write end dead
No of Employees '0'.
ErrorWS:java.io.IOException: Read end dead
I did some test code and I can reproduce the issue you're facing. But I don't see this problem IF the ObjectOutputStream and ObjectInputStream is instantiated in their respective threads. For example.
public void run() {
if (pout != null){
parseXmlFile();
parseDocument();
writeToStream();
}
if (pin != null){
readStream();
sortByAge();
printData();
}
}
public void writeToStream(){
try{
out = new ObjectOutputStream(pout);
out.writeObject(myEmpls);
out.flush();
out.close();
pout.flush();
pout.close();
}catch (Exception e) {
System.out.println("ErrorWS:" + e);
}
}
public void readStream(){
try{
in = new ObjectInputStream(pin);
myEmpls = (List<Employee>) in.readObject();
in.close();
pin.close();
}catch (Exception e) {
System.out.println("ErrorRS:" + e);
}
}
You will need to remove the instantiation of ObjectOutputStream and ObjectInputStream from the ParserRunnable constructor.

Parsing xml and making object java

Looking for someone to look over my simple code. I am rather new to what I am doing and know that I am probably just making a simple mistake somewhere.
I am parsing an xml file that is over http and trying to print out the text associated with the elements to the screen, and make an object that is populated by the text in those elements.
I can get all of the elements and associated text printed but the objects all have a null value in their fields. Let me know if I anything needs to be explained better.
Code is found below:
Object Class:
package com.entities;
public class StageOfLife
{
private String endDate;
private String offerData;
private String offerType;
private String redemption;
private String startDate;
private String termsConditions;
private String title;
private String merchantDescription;
private String merchantLogo;
private String merchantName;
public StageOfLife() {
}
public StageOfLife(String endDate, String offerData, String offerType,
String redemption, String startDate, String termsConditions,
String title, String merchantDescription, String merchantLogo,
String merchantName)
{
// Getters Setters HEre
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(endDate);
buffer.append("\n");
buffer.append(offerData);
buffer.append("\n");
buffer.append(offerType);
buffer.append("\n");
buffer.append(redemption);
buffer.append("\n");
buffer.append(startDate);
buffer.append("\n");
buffer.append(termsConditions);
buffer.append("\n");
buffer.append(title);
buffer.append("\n");
buffer.append(merchantDescription);
buffer.append("\n");
buffer.append(merchantLogo);
buffer.append("\n");
buffer.append(merchantName);
return buffer.toString();
}
}
And here is is the class with the methods and main:
package com.xmlparse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.entities.StageOfLife;
public class XmlParserStage
{
Document dom;
DocumentBuilder db;
List<StageOfLife> myStageList;
public XmlParserStage(){
//create a list to hold the StageOfLife objects
myStageList = new ArrayList<StageOfLife>();
}
private void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
db = dbf.newDocumentBuilder();
//parse to get DOM representation of the XML file
dom = db.parse("http:/url/goes/here");
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(SAXException se) {
se.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
private void parseDocument() {
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("Offer");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength(); i++) {
//get the elements
Element solEl = (Element)nl.item(i);
//get the StageOfLife object
StageOfLife sol = getStageOfLife(solEl);
//add it to list
myStageList.add(sol);
}
}
}
/*
take an <offer> element and read the values in, create
an StageOfLife object and return it
*/
private StageOfLife getStageOfLife(Element solEl) {
/*
for each <offer> element get the values
*/
String endDate = getTextValue(solEl,"EndDate");
String offerData = getTextValue(solEl,"OfferData");
String offerType = getTextValue(solEl,"OfferType");
String redemption = getTextValue(solEl,"Redemption");
String startDate = getTextValue(solEl,"StartDate");
String termsConditions = getTextValue(solEl,"TermsConditions");
String title = getTextValue(solEl,"Title");
String merchantDescription = getTextValue(solEl,"MerchantDescription");
String merchantLogo = getTextValue(solEl,"MerchantLogo");
String merchantName = getTextValue(solEl,"MerchantName");
//Create a new StageOfLife object with the value read from the xml nodes
StageOfLife sol = new StageOfLife(endDate, offerData, offerType,
redemption, startDate, termsConditions,
title, merchantDescription, merchantLogo,
merchantName);
return sol;
}
/*
take a xml element and the tag name, look for the tag and get
the text content
*/
private String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
System.out.print(el + ":" + textVal);
System.out.println();
}
return textVal;
}
/*
Calls getTextValue and returns a int value
*/
private int getIntValue(Element ele, String tagName) {
return Integer.parseInt(getTextValue(ele,tagName));
}
private void printData(){
System.out.println("Number of Offers: '" + myStageList.size() + "'.");
Iterator it = myStageList.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
public void run() {
//parse the xml file and get the dom object
parseXmlFile();
//get each stageoflife element and create a StageOfLife object
parseDocument();
//Iterate through the list and print the data
printData();
}
public static void main(String [] args) throws ClientProtocolException, IOException {
XmlParserStage xmlParser = new XmlParserStage();
xmlParser.httpClient();
xmlParser.run();
}
}
your constructor is not doing anything!
public StageOfLife(String endDate, String offerData, String offerType,
String redemption, String startDate, String termsConditions,
String title, String merchantDescription, String merchantLogo,
String merchantName)
{
// set the data
this.endDate = endDate;
...
}
But much better is to use Java XML Binding jaxb. it automatically maps java classes to xml
Take a look at Jaxb library. It can do all the heavy lifting for you.
JAXB Homepage
Vogella Tutorial
Mkyong Tutorial
Set the values you are passing to the StageOfLife constructor to the variables.
Try this
public class Tester {
String getString() throws IOException, ParserConfigurationException, SAXException {
InputStream inputStream = //your stream from http
String sa = "";
int cc;
while((cc = inputStream.read()) != -1) {
sa += (char) cc;
}
ByteArrayInputStream sr = new ByteArrayInputStream(sa.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(sr);
Node node=doc.getDocumentElement().getFirstChild();
String data=node.getNodeName();
return data;
}
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
Tester t = new Tester();
System.out.println(t.getString());
}

Java - Reading XML file

I am trying to read in some data from an XML file and having some trouble, the XML I have is as follows:
<xml version="1.0" encoding="UTF-8"?>
<EmailSettings>
<recipient>test#test.com</recipient>
<sender>test2#test.com</sender>
<subject>Sales Query</subject>
<description>email body message</description>
</EmailSettings>
I am trying to read these values as strings into my Java program, I have written this code so far:
private static Document getDocument (String filename){
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(filename));
}
catch (Exception e){
System.out.println("Error reading configuration file:");
System.out.println(e.getMessage());
}
return null;
}
Document doc = getDocument(configFileName);
Element config = doc.getDocumentElement();
I am struggling with reading in the actual string values though.
One of the possible implementations:
File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();
when used with the XML content:
<credentials>
<user>testusr</user>
<password>testpwd</password>
</credentials>
results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.
Reading xml the easy way:
http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
#XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
#XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
#XmlAttribute
public void setId(int id) {
this.id = id;
}
}
.
package com.mkyong.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
If using another library is an option, the following may be easier:
package for_so;
import java.io.File;
import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;
public class Q7704827_SimpleRead
{
public static void
main(String[] args)
{
String fileName = args[0];
TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
String recipient = emailNode.nextTextFieldE("recipient");
String sender = emailNode.nextTextFieldE("sender");
String subject = emailNode.nextTextFieldE("subject");
String description = emailNode.nextTextFieldE("description");
emailNode.verifyNoMoreChildren();
System.out.println("recipient = " + recipient);
System.out.println("sender = " + sender);
System.out.println("subject = " + subject);
System.out.println("desciption = " + description);
}
}
The library and its documentation are at rasmustorkel.com
Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you
I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:
<parent>
<child >
<child1> value 1 </child1>
<child2> value 2 </child2>
<child3> value 3 </child3>
</child>
<child >
<child4> value 4 </child4>
<child5> value 5</child5>
<child6> value 6 </child6>
</child>
</parent>
JAVA CODE:
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class saxParser {
static Map<String,String> tmpAtrb=null;
static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {
/**
* We can pass the class name of the XML parser
* to the SAXParserFactory.newInstance().
*/
//SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);
SAXParserFactory saxDoc = SAXParserFactory.newInstance();
SAXParser saxParser = saxDoc.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
String tmpElementName = null;
String tmpElementValue = null;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tmpElementValue = "";
tmpElementName = qName;
tmpAtrb=new HashMap();
//System.out.println("Start Element :" + qName);
/**
* Store attributes in HashMap
*/
for (int i=0; i<attributes.getLength(); i++) {
String aname = attributes.getLocalName(i);
String value = attributes.getValue(i);
tmpAtrb.put(aname, value);
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(tmpElementName.equals(qName)){
System.out.println("Element Name :"+tmpElementName);
/**
* Retrive attributes from HashMap
*/ for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
}
System.out.println("Element Value :"+tmpElementValue);
xmlVal.put(tmpElementName, tmpElementValue);
System.out.println(xmlVal);
//Fetching The Values From The Map
String getKeyValues=xmlVal.get(tmpElementName);
System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
tmpElementValue = new String(ch, start, length) ;
}
};
/**
* Below two line used if we use SAX 2.0
* Then last line not needed.
*/
//saxParser.setContentHandler(handler);
//saxParser.parse(new InputSource("c:/file.xml"));
saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
}
}
OUTPUT:
Element Name :child1
Element Value : value 1
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1
Element Name :child2
Element Value : value 2
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2
Element Name :child3
Element Value : value 3
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3
Element Name :child4
Element Value : value 4
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }

Categories

Resources