Java DOM parse html in xml node - java

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

Related

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 write xml attribute with value

This is my first post on Stack, so if there is something wrong, be patient ...
Ok, my question is how can I write an XML attribute with value. The result would be something like this:
<GroupAttribute>
<Attribute name = "Color"> Pink </Attribute>
.....
</GroupAttribute>
I tried this:
Element attribute = doc.createElement ("attribute");
groupAttribute.appendChild (attribute);
attribute.setAttribute ("attributeType" p.attributeColor);
groupAttribute.appendChild (getCompanyElements (doc, attribute, "attribute", p.attributeColor));
But it does not work.. the result is:
<GroupAttribute>
<Attribute> Pink </Attribute>
.....
</GroupAttribute>
the setAttribute is missing ...
What am I doing wrong?
Here the code:
import com.opencsv.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
*
* #author Mike
*/
public class prueba {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
List<Producto> prods = new ArrayList<Producto>();
try {
CSVReader reader;
reader = new CSVReader(new FileReader("C:\\Temp\\feeds\\Product_Prueba.csv"), ';');
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
//System.out.println(Arrays.toString(nextLine));
//Lee
Producto p;
p = new Producto();
p.attributeColor = "Pink";
prods.add(p);
}
} catch (IOException ex) {
Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(prueba.class.getName()).log(Level.SEVERE, null, ex);
}
xeraXML(prods);
}
static void xeraXML(List<Producto> ps) {
DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder icBuilder;
try {
icBuilder = icFactory.newDocumentBuilder();
Document doc = icBuilder.newDocument();
Element mainRootElement = doc.createElement("productRequest");
doc.appendChild(mainRootElement);
for (Iterator<Producto> i = ps.iterator(); i.hasNext();) {
Producto p;
p = i.next();
mainRootElement.appendChild(getProductElement(doc, p));
}
// output DOM XML to console
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(System.out);
//StreamResult out = new StreamResult("C:\\Temp\\results\\resultado.xml");
transformer.transform(source, console);
//transformer.transform(source, out);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Element getProductElement(Document doc /*String localizedFor,*/, Producto p) {
Element groupAttribute = doc.createElement("groupAttribute");
Element attribute = doc.createElement("attribute");
groupAttribute.appendChild(attribute);
attribute.setAttribute("attributeType", p.attributeColor);
groupAttribute.appendChild(getElements(doc, attribute, "attribute", p.attributeColor));
return groupAttribute;
}
private static Node getElements(Document doc, Element element, String name, String value) {
Element node = doc.createElement(name);
node.appendChild(doc.createTextNode(value));
return node;
}
}
And here the Producto class:
public class Producto {
public String attributeColor;
}
I just wanted to add the comment but am writing it as an answer since I don't have that privilege yet. I was looking to add the attribute to the xml node and I came across this post.
dependency = dom.createElement("dependency");
dependency.setAttribute("type", "value");
dependencies.appendChild(dependency);
I added the child after setting the attribute.

Can't make Java created XML work with XSL

I'm creating an XML using DOM, I open the XML with explorer and it seems fine.
After that I created an XSL for it, add the reference to it programatically to the XML and boom, it works no longer.
I inspect the code in the browser and save the file as XML.
I open the XML with notepad++ and noticed the npp shows the XML file is encoded in "UCS-2 LE BOM" even though the XML header sais it's in "UTF-8", I don't know if this has to do with being saved from the browser or it's because of Java transformer.File encoding according to npp
Anyway, I change the file encoding in npp to "UTF-8", open it again and it works flawlessly.
I've tried changing the transformer's encoding property transformer.setOutputProperty("encoding", "ISO-8859-1") to different values but it will just change the XML header.
I googled around but I haven't found anything that's worked so far.
This is the code where the XML is created
package modelo;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class DAOXML {
private static final String rutaUno = ".\\VerLibro.xml";
private static final String rutaListado = ".\\listado.xml";
public static boolean toXML(ArrayList<Libro> libros2) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final String rutaActual = libros2.size()>1?rutaListado:rutaUno;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
doc.setDocumentURI(rutaActual);
doc.setXmlStandalone(true);
Element libros = doc.createElement("libros");
for(Libro l : libros2) {
Element libro = doc.createElement("libro");
Element isbn = doc.createElement("isbn");
isbn.setTextContent(l.getISBN());
libro.appendChild(isbn);
Element editorial = doc.createElement("editorial_apellidos");
editorial.setTextContent(l.getEditorial_apellidos());
libro.appendChild(editorial);
Element autor = doc.createElement("autor");
autor.setTextContent(l.getAutor());
libro.appendChild(autor);
Element categoria = doc.createElement("categoria");
categoria.setTextContent(l.getCategoria());
libro.appendChild(categoria);
Element titulo = doc.createElement("titulo");
titulo.setTextContent(l.getTitulo());
libro.appendChild(titulo);
Element ubicacion = doc.createElement("ubicacion");
ubicacion.setTextContent(l.getUbiacion());
libro.appendChild(ubicacion);
libros.appendChild(libro);
}
doc.appendChild(libros);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// transformer.setOutputProperty("encoding", "ISO-8859-1");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(rutaActual));
//result.setWriter(new PrintWriter(new File(rutaActual), "UTF-8"));
transformer.transform(source, result);
if(rutaActual == rutaUno) {
Node pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"VerLibro.xsl\"");
doc.insertBefore(pi, libros);
}
else {
Node pi = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"listado.xsl\"");
doc.insertBefore(pi, libros);
}
Desktop.getDesktop().open(new File(rutaActual));
return true;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
Thanks in advance.
Try adding this line before you call transform():
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

how to pass a parsed doccument?

Hi all and thanks for your time and help.
Im trying to parse a xml file in the "res/raw" folder and passing the result to other class to work with it.
I'm stuck and cannot find any solution, Im trying to learn programming, so, the whole code may be wrong and I failed catastrophically from the beginning.
this is the parser, it get a document from the raw folder and return the parsed document.
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import android.app.Activity;
public class Pars extends Activity{
public Document doc(){
InputStream is = getResources().openRawResource(R.raw.talechap01);
Document docout = null;
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = domFactory.newDocumentBuilder();
docout = builder.parse(is);
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return docout;
}
}
this class get the parsed document and find some content using xpath and pass it in a return.
I can not pass the parsed document "docout" from the class "Pars"
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.Document;
import org.w3c.dom.NodeList;
public class Commanders {
public static String getStory(String spage) {
XPathExpression expr;
XPath xpath = XPathFactory.newInstance().newXPath();
Object result = null;
String num = spage;
String par = null;
Document doc = //Here I need the document parsed from the "Pars" class
try {
expr = xpath.compile("//decision"+num+"/p//text()");
result = expr.evaluate(doc, XPathConstants.NODESET);
}
catch (XPathExpressionException e) {
e.printStackTrace();
}
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
par = nodes.item(i).getNodeValue();
// System.out.println(par);
}
return par;
}
}
Here is an example from the xml.
I'm trying to get the content of "" depending of the "decisionXXX" number.
<talechap01>
<Start></Start>
<decision000 id="000">
<p> part 1 text</p>
<p> second row text</p>
<pick chs= "001" name= "go to decision001"/>
<pick chs= "002" name= "go to decision002"/>
</decision000>
<decision001 id="001">
<p>parte 2</p>
<pick chs = "002" name= "go to decision002"/>
<pick chs = "003" name= "go to decision003"/>
</decision001>
I'm doing something/all wrong?
Is there even possible to do?
Maybe I don't understand something, but it seems like attribute "id" is a decision number,
i mean next
decision000 id=000
If it's true then you can first find nodes which start with and then select by id
I can't check it now, but it should work, try next expression:
//*[starts-with(local-name(), 'decision')][#id='your_num_value']
You need to adjust the function signature of Commanders#getStory(java.lang.String) so it takes your extra doc argument. You can then execute your code like...
Pars pars = new Pars();
Document doc = pars.doc();
Commanders.getStory(doc, spage)

Java DOM: cannot write adapted XML to file

I have the following simplified XML:
<?xml version="1.0" encoding="UTF-8"?>
<ExportData>
<Rows>
<R>
<companyCodestringtrue>101</companyCodestringtrue>
<transactionQualifierstring>Sales</transactionQualifierstring>
<menuItemNumberlong>4302150</menuItemNumberlong>
<productQuantityinttrue>14</productQuantityinttrue>
<productValueInclVATdecimaltrue>1.90</productValueInclVATdecimaltrue>
<productValueExclVATdecimaltrue>1.775701</productValueExclVATdecimaltrue>
</R>
<R>
<companyCodestringtrue>101</companyCodestringtrue>
<transactionQualifierstring>Sales</transactionQualifierstring>
<menuItemNumberlong>333555</menuItemNumberlong>
<productQuantityinttrue>0</productQuantityinttrue>
<productValueInclVATdecimaltrue>3.90</productValueInclVATdecimaltrue>
<productValueExclVATdecimaltrue>3.775701</productValueExclVATdecimaltrue>
</R>
<R>
<companyCodestringtrue>101</companyCodestringtrue>
<transactionQualifierstring>Sales</transactionQualifierstring>
<menuItemNumberlong>1235665</menuItemNumberlong>
<productQuantityinttrue>5</productQuantityinttrue>
<productValueInclVATdecimaltrue>4.90</productValueInclVATdecimaltrue>
<productValueExclVATdecimaltrue>4.775701</productValueExclVATdecimaltrue>
</R>
</Rows>
</ExportData>
I need to delete each complete <R> element if the <productQuantityinttrue> element equals "0".
I came up with the following Java code:
package filterPositions;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class FilterPositions {
public static String result = "";
public static void main(String[] args) throws Exception {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
File filePath = new File("C:/LSA_SALES_EXPORT_1507_test_zero_qu.xml");
Document doc = docBuilder.parse(filePath);
Node rootNode = doc.getDocumentElement();
final Element element = doc.getDocumentElement();
// output new XML Document
DocumentBuilder parser = docFactory.newDocumentBuilder();
Document newdoc = parser.newDocument();
newdoc.adoptNode(traversingXML(element));
writeXmlFile(newdoc, "LSA_SALES_EXPORT_1507_test_zero_qu_OUT.xml");
System.out.println("Done...");
System.out.println("Exiting...");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Element traversingXML(Element element) {
NodeList positionen = element.getElementsByTagName("R");
Element e = null;
for (int i = 0; i < positionen.getLength(); i++) {
e = (Element) positionen.item(i);
for (Node child = e.getFirstChild(); child != null; child = child.getNextSibling()) {
if (child instanceof Element && "productQuantityinttrue".equals(child.getNodeName())&& "0".equals(child.getTextContent())) {
e.getParentNode().removeChild(e);
}
}
}
System.out.println(e);
return e;
}
public static void writeXmlFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource();
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance()
.newTransformer();
xformer.transform(source, result);
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}
}
}
I am not sure if my method "traversingXML" is working properly. My problem right now is that the adapted XML structure (one deleted) is not written to newdoc.
You don't copy the original document to newdoc; instead you create a new, empty XML document.
Instead, try this code:
...
final Element element = doc.getDocumentElement(); // original code up to here
traversingXML(element); // delete the node
writeXmlFile(doc, "LSA_SALES_EXPORT_1507_test_zero_qu_OUT.xml"); // save modified document

Categories

Resources