I was working on a Java Application and I have to map lots of data then generate an XML output.
All the output Looks good, except this 1 random element. As you can see in the image below all the "Value" tags look good, except the 1 highlighted.
http://i.stack.imgur.com/3TgIG.png
Code used to generate XML:
private void generateXML() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.newDocument();
//Add Root Element
Element rootElement = doc.createElement("Request");
rootElement.setAttribute("request_id", requestID);
doc.appendChild(rootElement);
//Add Experiment Element
Element experimentElement = doc.createElement("Experiment");
experimentElement.setAttribute("name", mappedData.getFileName()); //Change to experiment name
experimentElement.setAttribute("insert_method", "Insert");
experimentElement.setAttribute("notebook", "BioELN");
experimentElement.setAttribute("researcher", webFormPostData.get("Researchers")[0]);
experimentElement.setAttribute("project", getExcelTypeData.get("project"));
experimentElement.setAttribute("comments", webFormPostData.get("comments")[0]);
experimentElement.setAttribute("expt_date", getCurrentDate());
experimentElement.setAttribute("protocol_name", getExcelTypeData.get("protocolName"));
experimentElement.setAttribute("protocol_version", getExcelTypeData.get("protocolVersion"));
rootElement.appendChild(experimentElement);
//Add Data to Experiment
List<Element> experimentDataElements = generateExperimentDataElements();
for(Element dataElement : experimentDataElements) {
experimentElement.appendChild(dataElement);
}
Element attachmentElement = doc.createElement("Attachment");
attachmentElement.setAttribute("filename", mappedData.getFilePath());
experimentElement.appendChild(attachmentElement);
} catch(Exception e) {
logger.log("Error: " + e);
e.printStackTrace();
}
}
private List<Element> generateExperimentDataElements() {
//Loop through output_mapping mapped data and see if values are found in the mappedData.getMappedData();
List<Element> dataElements = new ArrayList<Element>();
for(int i=0; i < mappedData.getMappedData().size(); i++) { //Cycle Through all Mapped Data Rows
for(Map.Entry<String, Map<String, String>> entry : outputMappedFields.entrySet()) { //Get Required Fields
Element itemElement, valueElement, dataElement;
String mappedVarName = entry.getKey();
String vName = entry.getValue().get("variableName");
String variableType = entry.getValue().get("variableType");
itemElement = doc.createElement("VGItem");
itemElement.setAttribute("row_id", String.valueOf(i+1));
itemElement.setAttribute("table_name", "Results");
itemElement.setAttribute("variable_name", vName);
itemElement.setAttribute("parent_table_name", "Plate");
itemElement.setAttribute("parent_row_id", "plate");
valueElement = doc.createElement("Value");
dataElement = doc.createElement(variableType+"_value");
if(mappedData.getMappedData().get(i).containsKey(mappedVarName)) {
dataElement.setTextContent(mappedData.getMappedData().get(i).get(mappedVarName)); //Get field from Mapped Data
}
valueElement.appendChild(dataElement);
itemElement.appendChild(valueElement);
dataElements.add(itemElement);
}
}
return dataElements;
}
#Override
public String toString() {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + writer.getBuffer().toString().replaceAll("\n|\r", "");
return output;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
XML FILE: http://paste.strictfp.com/38339
Related
I am making some changes to an embedded XML file in my Java application. I have some fields, a LOAD button and a SAVE button. After clicking the save button I can see the XML file updating, but after clicking the load button the old values are being loaded to the fields.
Here is my code:
public class MyLoad_SaveSampleProject {
public String field1 = "";
public String field2 = "";
public void loadSampleProject() {
InputStream file = MyLoad_SaveSampleProject.class.getResourceAsStream("/main/resources/otherClasses/projects/SampleProject.xml");
try {
DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();
Document Doc = DocBuilder.parse(file);
NodeList list = Doc.getElementsByTagName("*"); //create a list with the elements of the xml file
for (int i=0; i<list.getLength(); i++) {
Element element = (Element)list.item(i);
if (element.getNodeName().equals("field1")) {
field1 = element.getChildNodes().item(0).getNodeValue().toString();
} else if (element.getNodeName().equals("field2")) {
field2 = element.getChildNodes().item(0).getNodeValue().toString();
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public void saveSampleProject(String field1Str, String field2Str) {
InputStream file = MyLoad_SaveSampleProject.class.getResourceAsStream("/main/resources/otherClasses/projects/SampleProject.xml");
try {
DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder();
Document Doc = DocBuilder.parse(file);
NodeList list = Doc.getElementsByTagName("*"); //create a list with the elements of the xml file
for (int i=0; i<list.getLength(); i++) {
Node thisAttribute = list.item(i);
if (thisAttribute.getNodeName().equals("field1")) {
thisAttribute.setTextContent(field1Str);
} else if (thisAttribute.getNodeName().equals("field2")) {
thisAttribute.setTextContent(field2Str);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(Doc);
StreamResult result = new StreamResult(new File("src/main/resources/otherClasses/projects/SampleProject.xml"));
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
public String returnField1() {
return field1;
}
public String returnField2() {
return field2;
}
}
And this is my default XML file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Strings>
<field1>string1</field1>
<field2>string2</field2>
</Strings>
When the save button is pressed I am using the saveSampleProject method. When the load button is pressed I am using the loadSampleProject method and then I am getting the field values with the returnField1 and returnField2 methods.
I have no idea of what could be wrong with what I'm doing. I would appreciate any suggestions.
Most probably that calling method getResourceAsStream() leads to resource caching. Since you are using File() in save method try to get InputStream on data load using File object, and not as resource.
I have the following code to convert text file to xml.:-
**
public static void main (String args[]) {
new ToXML().doit();
}
public void doit () {
try{
in = new BufferedReader(new FileReader("D:/sample.txt"));
out = new StreamResult("D:/data.xml");
initXML();
String str;
while ((str = in.readLine()) != null)
{
process(str);
}
in.close();
writeXML();
}
catch (Exception e) { e.printStackTrace(); }
}
public void initXML() throws ParserConfigurationException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
xmldoc = impl.createDocument(null, "AIRLINE_INFO", null);
root = xmldoc.getDocumentElement();
}
public void process(String s) {
String elements = s;
Element e1 = xmldoc.createElement("Supplier_Name");
Node n1 = xmldoc.createTextNode(elements);
e1.appendChild(n1);
Element e2 = xmldoc.createElement("E-Mail_Address");
Node n2 = xmldoc.createTextNode(elements);
e2.appendChild(n2);
e0.appendChild(e1);
e0.appendChild(e2);
root.appendChild(e0);
}
public void writeXML() throws TransformerConfigurationException,
TransformerException {
DOMSource domSource = new DOMSource(xmldoc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(domSource, out);
}
}
**
The output which is Expected is:
**
<AIRLINE_INFO>
<AIRTICKET>
<Supplier_Name>SpiceJet Ltd, 319, Udyog Vihar, Phase IV, Gurgaon - 122016 Haryana, India</Supplier_Name>
<E-Mail_Address>E-Mail: custrelations#spicejet.com</E-Mail_Address>
</AIRTICKET>
</AIRLINE_INFO>
**
But Currently While Excuting the code i am getting the following output
**
<AIRLINE_INFO>
<AIRTICKET>
<Supplier_Name>SpiceJet Ltd, 319, Udyog Vihar, Phase IV, Gurgaon - 122016 Haryana, India</Supplier_Name>
<E-Mail_Address>SpiceJet Ltd, 319, Udyog Vihar, Phase IV, Gurgaon - 122016 Haryana, India</E-Mail_Address>
</AIRTICKET>
<AIRTICKET>
<Supplier_Name>E-Mail: custrelations#spicejet.com</Supplier_Name>
<E-Mail_Address>E-Mail: custrelations#spicejet.com</E-Mail_Address>
</AIRTICKET>
</AIRLINE_INFO>
**
Please help how can i break the object in order to achieve the Expected output.
You use two times the same string for the text nodes here:
String elements = s;
Element e1 = xmldoc.createElement("Supplier_Name");
Node n1 = xmldoc.createTextNode(elements);
e1.appendChild(n1);
Element e2 = xmldoc.createElement("E-Mail_Address");
Node n2 = xmldoc.createTextNode(elements);
e2.appendChild(n2);
To fix that, you need to read two lines, and then create one air ticket node with that information.
I'm working on a bit of a project for my own amusement that involves outputting the contents of several variables to an XML file. However, when I put the program, the transformer only outputs the first line (the XML header) and nothing else. The saveData() method is called before writeFile(), and I've outputted the value of the variables to the console before calling writeFile() so I know they have a value.
Code below:
public class Output {
private static double citySizeMiles;
private static double citySizeAcres;
private CityType type;
private static int gpLimit;
private static long totalWealth;
private static long cityPopulation;
public static void saveData() {
cityPopulation = CityGenerator.cityPop;
citySizeMiles = City.getCitySizeMiles(cityPopulation);
citySizeAcres = City.getCitySizeAcres(cityPopulation);
gpLimit = City.getGoldLimit();
totalWealth = CityGenerator.cityWealth;
}
public static void writefile() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();
// Root Elements
Document doc = builder.newDocument();
Element root = doc.createElement("data");
// Data Element
Element data = doc.createElement("City");
root.appendChild(data);
Attr attr = doc.createAttribute("name");
attr.setValue("Test");
data.setAttributeNode(attr);
// City size (sq miles)
Element sizeMi = doc.createElement("sizeMiles");
sizeMi.appendChild(doc.createTextNode(String.valueOf(citySizeMiles)));
data.appendChild(sizeMi);
// City size (acres)
Element sizeAc = doc.createElement("sizeAcres");
sizeAc.appendChild(doc.createTextNode(String.valueOf(citySizeAcres)));
data.appendChild(sizeAc);
// Population
Element pop = doc.createElement("population");
pop.appendChild(doc.createTextNode(String.valueOf(cityPopulation)));
data.appendChild(pop);
// GP limit
Element gpLim = doc.createElement("gpLimit");
gpLim.appendChild(doc.createTextNode(String.valueOf(gpLimit)));
data.appendChild(gpLim);
// Total fluid wealth
Element wealth = doc.createElement("totalWealth");
wealth.appendChild(doc.createTextNode(String.valueOf(totalWealth)));
data.appendChild(wealth);
// Write to XML file
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", 4);
Transformer trans = tf.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");
DOMSource source = new DOMSource(doc);
//StreamResult result = new StreamResult(new File("D:\\test.xml"));
StreamResult result = new StreamResult(System.out);
trans.transform(source, result);
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(TransformerException tfe) {
tfe.printStackTrace();
}
}
}
I'm no expert on DOM (I avoid it like the plague, and encourage everyone else to do likewise) but I think you have failed to connect the root element to the document node.
I am reading an XML file using Stax parser and writing it using DOM in java. I am not getting desired XML output. I read following XML file
<config>
<Sensor1>
<name>abc</name>
<range>100</range>
</Sensor1>
<sensor2>
<name>xyz</name>
<range>100</range>
</sensor2>
</config>
I parse the above XML file using Stax parser as follows
public void readConfig(String configFile) {
boolean sensor1 = false;
boolean sensor2 = false;
try
{
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream(configFile);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
if (startElement.getName().getLocalPart() == (sensor1)) {
sensor1 = true;
Sensor1 Obj1 = new Sensor1();
}
if (startElement.getName().getLocalPart() == (sensor2)) {
sensor2 = true;
Sensor2 Obj2 = new Sensor2();
}
if (sensor1) {
if (event.asStartElement().getName().getLocalPart().equals(name)) {
event = eventReader.nextEvent();
Obj1.set_Sensor_Name(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(range)) {
event = eventReader.nextEvent();
Obj1.set_Sensor_Range(event.asCharacters().getData());
continue;
}
}
if (sensor2) {
if (event.asStartElement().getName().getLocalPart().equals(name)) {
event = eventReader.nextEvent();
Obj2.set_Sensor_Name(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart().equals(range)) {
event = eventReader.nextEvent();
Obj1.set_Sensor_Range(event.asCharacters().getData());
continue;
}
}
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart() == (sensor1)) {
sensor1.addToArray();
}
if (endElement.getName().getLocalPart() == (sensor2)) {
sensor2.addToArray();
}
}
}
In "Sensor1" and "Sensor2" class I am adding extra information depending on some condition.
class Sensor1 {
public ArrayList<Object> list = new ArrayList<Object>();
String name;
double range;
public void set_Sensor_Name(String name) {
this.name = name;
}
public void set_Sensor_Range(double range) {
this.range = range;
}
public void addToArray(){
double distance =50;
if(distance<range){
list.add("TITANIC");
list.add(123456);
}
WriteFile fileObj = new WriteFile();
fileObj.writeXMlFile(list);
}
}
This is the class to write the XML
public class WriteFile {
public void writeXmlFile(ArrayList<Object> list) {
try {
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
Element root = doc.createElement("SensorTracks");
doc.appendChild(root);
Element sensorInfo = doc.createElement("SensorDetails");
root.appendChild(sensorInfo);
Element vesselInfo = doc.createElement("VesselDetails");
root.appendChild(vesselInfo);
for(int i=0; i<list.size(); i +=4 ) {
Element name = doc.createElement("SensorName");
name.appendChild(doc.createTextNode(String.valueOf(list.get(i))));
sensorInfo.appendChild(name);
Element range = doc.createElement("SensorRange");
name.appendChild(doc.createTextNode(String.valueOf(list.get(i+1))));
sensorInfo.appendChild(range);
Element mmi = doc.createElement("shipname");
mmi.appendChild(doc.createTextNode(String.valueOf(list.get(i+2))));
vesselInfo.appendChild(mmi);
Element license = doc.createElement("license");
license.appendChild(doc.createTextNode(String.valueOf(list.get(i+3))));
vesselInfo.appendChild(license);
}
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
// format the XML nicely
aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
aTransformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
try {
FileWriter fos = new FileWriter("/home/ros.xml");
StreamResult result = new StreamResult(fos);
aTransformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
}
} catch (TransformerException ex) {
System.out.println("Error outputting document");
} catch (ParserConfigurationException ex) {
System.out.println("Error building document");
}
When I execute, I get following XML
<SensorTracks>
<sensorDetails>
<SensorName>xyz</SensorName>
<SensorRange>100</SensorRange>
</sensorDetails>
<VesselDetails>
<shipname>TITANIC</shipname>
<license>123456</license>
</vesselDetails>
MY FINAL OUTPUT MUST BE
<config>
<SensorTracks>
<sensorDetails>
<SensorName>xyz</SensorName>
<SensorRange>100</SensorRange>
<SensorName>abc</SensorName>
<SensorRange>100</SensorRange>
</sensorDetails>
<VesselDetails>
<shipname>TITANIC</shipname>
<license>123456</license>
</vesselDetails>
What wrong thing I am I doing in my code ?? Any help is appreciated. Thanks in advance
I am answering my own question again. The problem is very simple. To get the desired output as mention above. just make the following changes to "WriteFile" class.
FileWriter fos = new FileWriter("/home/ros.xml" ,true);
Finally, I am learning Java :)
Frankly speaking the example looks cumbersome. Do you consider to use apache digester of jaxb?
http://commons.apache.org/digester/
http://www.oracle.com/technetwork/articles/javase/index-140168.html
I'm having an xml which i parse and get the data from between the nodes. However this data is surrounded by html tags. i create another xml and put this data in it. Now i have to get parse it again to get the proper html syntax.
Kindly help.
public class XMLfunctions {
public final static Document XMLfromString(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("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
/*Start Parsing Body */
public static String getBodyXML(String id){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.44:9090/solr/core0/select/?q=content_id:"+id+"&version=2.2&start=0&rows=10&indent=on");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
String st= ParseXMLBodyNode(line,"doc");
return st;
}
public static String ParseXMLBodyNode(String str,String node){
String xmlRecords = str;
String results = "";
String[] result = new String [1];
StringBuffer sb = new StringBuffer();
StringBuffer text = new StringBuffer();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList indiatimes1 = doc.getElementsByTagName(node);
sb.append("<results count=");
sb.append("\"1\"");
sb.append(">\r\n");
for (int i = 0; i < indiatimes1.getLength(); i++) {
Node node1 = indiatimes1.item(i);
if (node1.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node1;
NodeList nodelist = element.getElementsByTagName("str");
Element element1 = (Element) nodelist.item(0);
NodeList title = element1.getChildNodes();
title.getLength();
for(int j=0; j<title.getLength();j++){
text.append(title.item(j).getNodeValue());
}
System.out.print((title.item(0)).getNodeValue());
sb.append("<result>");
sb.append("<news>");
String tmpText = html2text(text.toString());
//sb.append("<![CDATA[<body>");
sb.append(tmpText);
//sb.append("</body>]]>");
sb.append("</news>");
sb.append("</result>\r\n");
result[i] = title.item(0).getNodeValue();
}
}
sb.append("</results>");
} catch (Exception e) {
System.out.println("Exception........"+results );
e.printStackTrace();
}
return sb.toString();
}
public static String html2text(String html) {
String pText = Jsoup.clean(html, Whitelist.basic());
return pText;
}
My class which inititates the process
public class NewsDetails extends ListActivity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
/*}
#Override
protected void onStart() {*/
super.onStart();
Intent myIntent = getIntent();
String id = myIntent.getStringExtra("content_id");
String title = myIntent.getStringExtra("title");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getBodyXML(id);
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(NewsDetails.this, "No Result Found", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", title);
Element e = (Element)nodes.item(i);
map.put("news", XMLfunctions.getValue(e, "news"));
mylist.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_item, new String[] { "title", "news" }, new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
Sample xml which i get after converting from jsoup
<results count="1">
<result>
<news>
<ul><li><p>as part of its growth plan,</p></li><li><p>in a bid to achieve the target</p></li><li><p>it is pointed out that most of ccl's production came from opencast mines and only 2 mt from underground (ug) mines. ccl is now trying to increase the share underground production. the board of ccl has, thus, approved the introduction of continuous mine in chiru ug at a cost of about rs 145 crore to raise this mine's production from 2 mt to 8 mt per annum.</p></li><li><p>mr ritolia said that.</p></li></ul>
</news>
</result>
</results>
I want to extract the content between the news tags. This xml is fed to XMLfromString(String xml) function in XMLFunctions class which then returns only "<" and rest of the body is left.
I'm not able to get the body with html tags to provide formatting.
One option is to use XML CDATA section as:
<result>
<news><![CDATA[
<ul><li><p>as part of its growth plan,</p></li><li><p>in a bid to achieve the target</p></li><li><p>it is pointed out that most of ccl's production came from opencast mines and only 2 mt from underground (ug) mines. ccl is now trying to increase the share underground production. the board of ccl has, thus, approved the introduction of continuous mine in chiru ug at a cost of about rs 145 crore to raise this mine's production from 2 mt to 8 mt per annum.</p></li><li><p>mr ritolia said that.</p></li></ul>
]]>
</news>
</result>
</results>
Then your parser will not treat HTML tags as XML and allow you access to raw content of the element. The other option is to encode the HTML tags i.e. convert all < into <, > into >, & into & etc. For more on encoding see here