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();
}
Related
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
I am very new to XML parsing. I am trying to read the XML file from a shared drive on my computer and moving them to another shared drive. I have the below XML file. i am trying to read the Test.pdf value from this XML document
<?xml version="1.0" encoding="utf-8" ?>
<xml>
<IndexData FileName="Test.pdf">
<AttachmentID>3221929</AttachmentID>
<URI>test234555..pdf</URI>
<postmarkDate>2018-07-02T12:52:00.9</postmarkDate>
<pin>305270036</pin>
<scanDate>2018-07-02T12:52:00.9</scanDate>
<UserLogin>admin</UserLogin>
</IndexData>
<IndexData FileName="Test2.pdf">
<AttachmentID>3221931</AttachmentID>
<URI>Appp2.pdf</URI>
<postmarkDate>2018-07-02T14:19:22.5</postmarkDate>
<pin>305270036</pin>
<scanDate>2018-07-02T14:19:22.5</scanDate>
<UserLogin>admin</UserLogin>
</IndexData>
</xml>
I tried importing import org.w3c.dom.Node; for this. Below is my code:
String processXml(Node doc) {
String fileName = null;
try {
DfLogger.debug(this, "Loading: " + doc.getNodeName(), null, null);
Map<String, String> indexData = getXmlData(doc);
fileName = indexData.get("IndexData FileName");
if (new File(fileName).exists()) {
import(fileName, indexData);
}
} catch (Exception ex) {
DfLogger.error(this, "Error processing document.", null, ex);
return null;
}
return fileName;
}
My value for FileName is always NULL when I am trying to read the value by doing this:
fileName = indexData.get("IndexData FileName");
below is my getXmlData method.
protected Map<String, String> getXmlData(Node xmlDataNode) {
Map<String, String> xmlData = new HashMap<>();
NodeList nodeList = xmlDataNode.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
xmlData.put(node.getNodeName(), node.getTextContent().trim());
}
}
return xmlData;
}
The caller method for processXML is below:
Public void processIncomingfiles(String documentTagName) throws Exception {
DfLogger.debug(this, "Import Process Begin ---- exportPath=" + exportPath, null, null);
try {
File dir = new File(exportPath);
if (dir.isDirectory()) {
FilenameFilter xmlFiles = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xml");
}
};
for (File file : dir.listFiles(xmlFiles)) {
if (!file.isDirectory()) {
DfLogger.debug(this, "Loading XML file: " + file.getAbsolutePath(), null, null);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();
FileInputStream fileStream = new FileInputStream(file);
try {
// Use FileInputStream instead of File since parse will leave file locked on error
Document doc = documentBuilder.parse(fileStream);
fileStream.close();
fileStream = null;
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName(documentTagName);
List<Node> errors = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
String documentFilename = processXml(nodeList.item(i));
if (documentFilename != null) {
moveFileToProcessedSuccessful(documentFilename);
} else {
DfLogger.debug(
this,
"Error processing document in file: " + file.getName(),
null,
null);
errors.add(nodeList.item(i));
}
}
if (!errors.isEmpty()) {
if (errors.size() == nodeList.getLength()) {
safeMove(file, file.getAbsolutePath() + ".errors");
} else {
Node parent = nodeList.item(0).getParentNode();
for (Node errorDoc : errors) {
parent.removeChild(errorDoc);
}
writeXml(doc, file.getAbsolutePath());
moveFileToProcessedSuccessful(file);
while (nodeList.getLength() > 0) {
parent.removeChild(nodeList.item(0));
}
for (Node errorDoc : errors) {
parent.appendChild(errorDoc);
}
writeXml(doc, file.getAbsolutePath() + ".errors");
}
} else {
moveFileToProcessedSuccessful(file);
}
} catch (Exception ex) {
DfLogger.error(this, "Error parsing XML File.", null, ex);
if (fileStream != null) {
fileStream.close(); // If DocBuilder.parse fails, leaves file locked
}
safeMove(file, file.getAbsolutePath() + ".error");
}
}
}
}
} catch (Exception ex) {
DfLogger.error(this, "Error in XML Parser.", null, ex);
throw ex;
}
DfLogger.debug(this, "Import Process Ends -----------", null, null);
}
/**
* Process the Xml for the give document node.
* #param doc xml node
* #return filename of successfully processed document, otherwise null
*/
any help will be appreciated.
Lets assume you have your xml data in test.xml file. You can read file and get specific data from your xml using the below code:
package yourPackage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(Files.newInputStream(Paths.get("test.xml")));
doc.getDocumentElement().normalize();
Element data = (Element)doc.getElementsByTagName("IndexData").item(0);
System.out.println(data.getAttribute("FileName"));
}
}
The output is :
Test.pdf
Java Programming
I have a class WeatherAgent. The function of this class is to get the current temperature value and other parameters from a URL (XML code) from World weather online.
My main question is; how to get the generated temperature value in class WeatherAgent into antother class (Boiler)? So, Accessing XML value in class WeatherAgent as a new variable in another class (class Boiler).
package assignment_4;
/*
* imports of class WeatherAgent2
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
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;
/*
*start class WeatherAgent2
*/
public class WeatherAgent {
private Document getDocument() {
Document doc = null;
try {
URL url = new URL(
"http://api.worldweatheronline.com/free/v1/weather.ashx?q=Eindhoven&format=xml&num_of_days=5&key=87xdd77n893f6akfs6x3jk9s");
URLConnection connection = url.openConnection(); // Connecting to
// URL specified
doc = parseXML(connection.getInputStream());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return doc;
}
private Document parseXML(InputStream stream) throws Exception
{
DocumentBuilderFactory objDocumentBuilderFactory = null;
DocumentBuilder objDocumentBuilder = null;
Document doc = null;
try
{
objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();
doc = objDocumentBuilder.parse(stream);
}
catch (Exception ex)
{
throw ex;
}
return doc;
}
/*
* get the temperature
*/
public double temperature() {
Document doc = getDocument();
Node Temperature;
Double temp = 0.0;
NodeList forecast = doc.getElementsByTagName("temp_C");
for (int i = 0; i < forecast.getLength(); i++) {
Element element = (Element) forecast.item(i);
NodeList list1 = (NodeList) element.getChildNodes();
Temperature = list1.item(0);
temp = Double.parseDouble(Temperature.getNodeValue());
}
return temp;
}
/*
* get cloud cover
*/
public double cloudcover() {
Document doc = getDocument();
Node Cloudcover;
Double cloudcover = 0.0;
NodeList forecast = doc.getElementsByTagName("cloudcover");
for (int i = 0; i < forecast.getLength(); i++) {
Element element = (Element) forecast.item(i);
NodeList list2 = (NodeList) element.getChildNodes();
Cloudcover = list2.item(0);
cloudcover = Double.parseDouble(Cloudcover.getNodeValue());
}
return cloudcover;
}
/*
* print method
*/
public static void main(String[] argvs) {
WeatherAgent wp = new WeatherAgent();
System.out.println("Temperature: " + wp.temperature());
System.out.println("Cloudcover: " + wp.cloudcover());
}
}
I have this methode in class Boiler to get the temperature value from class WeatherAgent into class Boiler.
It is not working and I do know why. Thanks already for your help!
public double getValueFromAgent(){
double agentTemp = send(URL.create("http://api.worldweatheronline.com/free/v1/weather.ashx?q=Eindhoven&format=xml&num_of_days=5&key=87xdd77n893f6akfs6x3jk9s", "temperature" , null, Double.class));
return agentTemp;
}
There are design patterns for how to structure your classes to share information like this. I'd look into the Observer pattern and the Mediator pattern.
Or in main, when you get the temperature from the WeatherAgent, push it into Boiler. With all of these, the idea is to decouple Boiler from knowing anything about WeatherAgent. It helps with reusability, and makes testing them independently a lot easier.
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);
i have a parser here:
package lt.prasom.functions;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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;
import org.xml.sax.SAXException;
import android.annotation.TargetApi;
import android.media.MediaRecorder.OutputFormat;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
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
*/
#TargetApi(8)
public final String getElementValue( Node elem , boolean html) {
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 child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0), false);
}
}
And there's my sample xml :
<items>
<item>
<name>test</name>
<description>yes <b>no</b></description>
</item>
</items>
When i parse description i'm getting everything to tag ("yes"). So i want to parse raw data in description tag. I tried CDATA tag didin't worked. Is it any way without encoding xml?
Thanks!
I agree with the comments about this question not being complete, or specific enough for a direct answer (like modifying your source to work etc.), but I had to do something somewhat similar (I think) and can add this. It might help.
So if, IF, the content of the "description" element were valid XML all by itself, so say the document actually looked like:
<items>
<item>
<name>test</name>
<description><span>yes <b>no</b></span></description>
</item>
</items>
then you could hack out the content of the "description" element as a new XML Document and then get the XML text form that which would look then like:
<span>yes <b>no</b></span>
So a method something like:
/**
* Get the Description as a new XML document
*
*/
public Document retrieveDescriptionAsDocument(Document sourceDocument) {
Document document;
Node tmpNode;
Document document2 = null;
try {
// get the description node, I am just using XPath here as it is easy
// to read, you already have a reference to the node so just continue as you
// were doing for that, bottom line is to get a reference to the node
tmpNode = org.apache.xpath.XPathAPI.selectSingleNode(sourceDocument,"/items/item/description");
if (tmpNode != null) {
// create a new empty document
document2 = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
// associate the node with the original document
sourceDocument.importNode(tmpNode, true);
// create a document fragment from the original document
DocumentFragment df = sourceDocument.createDocumentFragment();
// append the node you found, to the fragment
df.appendChild(tmpNode);
// create the Node to append to the new DOM
Node importNode = document2.importNode(df,true);
// append the fragment (as a node) to the new empty document
Document2.appendChild(importNode);
}
else {
// LOG WARNING
yourLoggerOrWhatever.warn("retrieveContainedDocument: No data found for XPath:" + xpathP);
}
} catch (Exception e) {
// LOG ERROR
yourLoggerOrWhatever.error("Exception caught getting contained document:",e);
}
// return the new doc, and the caller can then output that new document, that will now just contain "<span>yes <b>no</b></span>" as text, apply an XSL or whatever
return document2;
}