blank string in XML parsing in android - java

I am trying to make an XML parser. However, the following code just gives blank output.
The "heyya" message in the getElementValue() function is getting printed which tells that empty string is returned. Please help.
import java.io.IOException;
import java.io.StringReader;
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.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLParser {
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){
System.out.println(e.getMessage());
return null;
} catch(SAXException e){
System.out.println(e.getMessage());
return null;
} catch(IOException e){
System.out.println(e.getMessage());
return null;
}
return doc;
}
public String getValue(Element item, String str)
{
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
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();
}
}
}
}
//System.out.println("heyya");
return "";
}
}
class createData
{
static final String KEY_ID = "id"; //parent node
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
public void createArrayList()
{
//ArrayList<HashMap<String, String>> userData = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
//obtain xml as string here
String xml="<menu>\n\t<item>\n\t\t<id>1</id>\n\t\t<name>Margherita</name>\n\t\t<cost>155</cost>\n\t\t<description>Single cheese topping</description>\n\t</item></menu>\n";
Document doc = parser.getDomElement(xml);
NodeList node_L = doc.getElementsByTagName(KEY_ID);
for(int i=0; i<node_L.getLength(); i++)
{
//HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)node_L.item(i);
String name = parser.getValue(e, KEY_NAME);
String cost = parser.getValue(e, KEY_COST);
String description = parser.getValue(e, KEY_DESC);
System.out.println(name+" "+cost+" "+description);
//map.put(KEY_NAME, name);
//map.put(KEY_COST, cost);
//map.put(KEY_DESC, description);
//userData.add(map);
}
System.out.println("hello pop!");
//System.out.println(userData.get(0));
}
public static void main(String args[])throws IOException
{
createData ob =new createData();
ob.createArrayList();
}
}

This is the problem.
NodeList node_L = doc.getElementsByTagName(KEY_ID);
You are getting id here, but the id is just a subtag in your item. Replace that with this:-
NodeList node_L = doc.getElementsByTagName("item");
Note:- Your parent node is ITEM and not ID.
You can get your ID as you get your other tags.
String id = parser.getValue(e, KEY_ID);

Related

Java - Delete child node from dynamic XML

I want to delete a XML node that contains a PDF in Base64. This is an example:
<?xml version="1.0" encoding="UTF-8"?>
<getResult>
<id>null</id>
<pdf>ioje98fh23fjkiwf72322342</pdf>
</getResult>
First, I transform the XML in String to Document but the result is null. This is my code:
DocumentBuilder dbf = null;
Document doc = null;
try {
dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<getResult><id>null</id><pdf>ioje98fh23fjkiwf72322342</pdf></getResult>"));
doc = dbf.parse(is);
NodeList children = doc. getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node currentChild = children.item(i);
System.out.println(currentChild);
}
} catch (Exception e) {
System.out.println(e.getMessage().toString());
}
The result is always: [getResult: null]
Considering that the main node can vary but the structure does not, How can I get the PDF node?
Here is the could you could use to retrieve the data.
import java.io.StringReader;
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;
import org.xml.sax.InputSource;
import org.w3c.dom.CharacterData;
public class LabFour {
public static void main(String[] args) {
DocumentBuilder dbf = null;
Document doc = null;
try {
dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(
new StringReader("<getResult><id>null</id><pdf>ioje98fh23fjkiwf72322342</pdf></getResult>"));
doc = dbf.parse(is);
NodeList nodes = doc.getElementsByTagName("getResult");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("id");
Element line = (Element) name.item(0);
System.out.println("id: " + getCharacterDataFromElement(line));
NodeList pdf = element.getElementsByTagName("pdf");
line = (Element) title.item(0);
System.out.println("pdf: " + getCharacterDataFromElement(pdf));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
}
SimpleXml can do it:
final SimpleXml simple = new SimpleXml();
final Element element = simple.fromXml(data);
element.children.remove(1);
System.out.println(simple.domToXml(element));
Will output:
<getResult><id>null</id></getResult>
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>

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: Function that parses XML data - nothing being outputted

I'm relatively new to XML processing with Java, so expect some mistakes, but anyway...I'm trying to parse the following XML data:
http://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx
I would like to accomplish this using a function, where the name of the XML tag and NodeList are passed in as parameters, and it returns the content.
Thanks.
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class Files {
#SuppressWarnings("unused")
public static void main (String [] args) throws IOException, ParserConfigurationException, SAXException{
String address = "/home/leo/workspace/Test/Files/src/file.xml";
String author = "author";
String title = "title";
String genre = "genre";
String price = "price";
String publish = "publish_date";
String descr = "description";
File xmlFile = new File(address);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getNodeName());
NodeList n = doc.getElementsByTagName("book");
System.out.println("Number of books " + n.getLength());
getElement(author, n);
}
private static void getElement(String elementName, NodeList n){
for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);
Element showElement = (Element)showNode;
System.out.println(elementName + ": " +
showElement.getAttribute(elementName)
);
}
}
}
The problem is : showElement.getAttribute(elementName)
you want to get the value of a node,but getAttribute is to get the attribute of the node,you should figure out what attribute means in XML.
you can get the value like this:
private static void getElement(String elementName, NodeList n){
for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);
NodeList nl = showNode.getChildNodes();
for(int j=0;j<nl.getLength();j++)
{
Node nd=nl.item(j);
if(nd.getNodeName().equals(elementName))
{
System.out.println(elementName + ":" + nd.getTextContent());
}
}
}
}
}

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());
}

Parsing XML using java DOM

Im new in Java, and i have a task to Parse one xml file using http with current url http://belbooner.site40.net/testXmls/details.xml
I created Some class to parse it using Dom method, but im having java.lang.NullPointerException while trying to get one Nodes value
So here's the code
import java.security.KeyStore.Builder;
import java.util.*;
import java.io.*;
import java.net.*;
import javax.swing.text.Document;
import javax.xml.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.w3c.dom.*;
import org.w3c.dom.CharacterData;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class RequestResponse {
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
RequestResponse req= new RequestResponse();
req.getHTTPXml(url);
}
void getHTTPXml(URL url) throws ParserConfigurationException, IOException, SAXException {
//URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ACCEPT","application/xml");
InputStream xml = conn.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(xml);
System.out.println(document);
String doctype = conn.getContentType();
System.out.print(doctype);
NodeList root = document.getChildNodes();
Node server = getNodes("server",root);
Node check = getNodes("check", server.getChildNodes());
NodeList nodes = check.getChildNodes();
String checkid= getNodeValue("checkid", nodes);
System.out.println(checkid);
conn.disconnect();
//return (Document) DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xml);
}
Node getNodes(String tagName, NodeList nodes) {
for(int i=0; i< nodes.getLength();i++) {
Node node= nodes.item(i);
if(node.getNodeName().equalsIgnoreCase(tagName)) {
return node;
}
}
return null;
}
String getNodeValue(String tagName, NodeList nodes ) {
for ( int i = 0; i < nodes.getLength(); i++ ) {
Node node = nodes.item(i);
if (node.getNodeName().equalsIgnoreCase(tagName)) {
NodeList childNodes = node.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++ ) {
Node data = childNodes.item(y);
if ( data.getNodeType() == Node.TEXT_NODE ) {
return data.getNodeValue();
}
if(data instanceof CharacterData) {
CharacterData cd= (CharacterData) data;
return cd.getData();
}
}
}
}
return "";
}
}
The stacktrace I'm getting is the following:
application/xmlException in thread "main" java.lang.NullPointerException at
RequestResponse.getHTTPXml(RequestResponse.java:45) at
RequestResponse.main(RequestResponse.java:22)
After changin Node server = getNodes("server",root); to `
Node resultNode = getNodes("result", root);
Node server = getNodes("server", resultNode.getChildNodes());`
`application/xmlException in thread "main" java.lang.NullPointerException
at RequestResponse.getHTTPXml(RequestResponse.java:49)
at RequestResponse.main(RequestResponse.java:22)
`
Please help me to find the issue.
The problem is that Node server = getNodes("server",root); is returning null.
Why does this happen? Well look how you implemented getNodes
Node getNodes(String tagName, NodeList nodes) {
for(int i=0; i< nodes.getLength();i++) {
Node node= nodes.item(i);
if(node.getNodeName().equalsIgnoreCase(tagName)) {
return node;
}
}
return null;
}
You are giving as input the document root which is a single "Result" node, you iterate through it and you compare if the node's name is in this case "server" which never will be, hence you return null and get a NPE.
Your node look up must be done in the following way:
NodeList root = document.getChildNodes();
// Keep in mind that you have the following structure:
// result
// server
// checks
// check
// checkId
// check
// checkId
Node resultNode = getNodes("result", root);
Node server = getNodes("server", resultNode.getChildNodes());
Node checks = getNodes("checks", server.getChildNodes());
NodeList childNodes = checks.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node possibleCheck = childNodes.item(i);
if (possibleCheck.getNodeName().equals("check")) {
String checkid = getNodeValue("checkid", possibleCheck.getChildNodes());
System.out.println(checkid);
}
}
This way you'll be iterating through the correct node list.
Using XPath is more efficient and flexible (than normal iteration) while parsing xml.
XPath Tutorial from IBM
XPath Reference Orielly tutorial
Xpath Reference Oracle java tutorial
Try below code.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class RequestResponse {
public static void main(String[] args) throws ParserConfigurationException,
IOException, SAXException {
URL url = new URL("http://belbooner.site40.net/testXmls/details.xml");
RequestResponse req = new RequestResponse();
req.getHTTPXml(url);
}
void getHTTPXml(URL url) throws ParserConfigurationException, IOException,
SAXException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ACCEPT", "application/xml");
InputStream xml = conn.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(xml);
System.out.println(document);
String doctype = conn.getContentType();
System.out.println(doctype);
XPathFactory pathFactory = XPathFactory.newInstance();
XPath path = pathFactory.newXPath();
XPathExpression expression;
try {
expression = path.compile("/result/server/checks/check/checkid");
NodeList nodeList = (NodeList) expression.evaluate(document,
XPathConstants.NODESET);
String checkids[] = getNodeValue(nodeList);
for (String checkid : checkids) {
System.out.print(checkid + ", ");
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
conn.disconnect();
}
String[] getNodeValue(NodeList nodes) {
String checkIds[] = new String[nodes.getLength()];
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
checkIds[i] = node.getTextContent();
}
return checkIds;
}
}

Categories

Resources