Creating an xml document in android - java

So I'm trying to create an xml document in my android application. I'm using the code that I used when writing a java application. I tried as shown below:
public void createxml() throws SAXException, IOException {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "images" + File.separator + "newxml.xml");
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
// root elements
// Document doc = docBuilder.newDocument();
// Element rootElement = doc.get
// doc.appendChild(rootElement);
Node node = doc.getDocumentElement();
// staff elements
Element outfit = doc.createElement("outfit");
node.appendChild(outfit);
// set attribute to staff element
/*
* Attr attr = doc.createAttribute("id"); attr.setValue("1");
* staff.setAttributeNode(attr);
*/
// shorten way
// staff.setAttribute("id", "1");
// firstname elements
if (savename.equals("none")) {
} else {
Element nameelement = doc.createElement("name");
nameelement.appendChild(doc.createTextNode(savename));
outfit.appendChild(nameelement);
}
if (hatloc.equals("none")) {
} else {
Element hatelement = doc.createElement("hat");
hatelement.appendChild(doc.createTextNode(hatloc));
outfit.appendChild(hatelement);
}
if (shirtloc.equals("none")) {
} else {
Element shirtelement = doc.createElement("shirt");
shirtelement.appendChild(doc.createTextNode(shirtloc));
outfit.appendChild(shirtelement);
}
if (pantloc.equals("none")) {
} else {
Element pantselement = doc.createElement("pants");
pantselement.appendChild(doc.createTextNode(pantloc));
outfit.appendChild(pantselement);
}
if (shoeloc.equals("none")) {
} else {
Element shoeselement = doc.createElement("shoes");
shoeselement.appendChild(doc.createTextNode(shoeloc));
outfit.appendChild(shoeselement);
}
if (acc1loc.equals("none")) {
} else {
Element accelement = doc.createElement("accessories");
accelement.appendChild(doc.createTextNode(acc1loc));
outfit.appendChild(accelement);
}
if (acc2loc.equals("none")) {
} else {
Element acc2element = doc.createElement("accessories2");
acc2element.appendChild(doc.createTextNode(acc2loc));
outfit.appendChild(acc2element);
}
if (beltloc.equals("none")) {
} else {
Element beltelement = doc.createElement("belt");
beltelement.appendChild(doc.createTextNode(beltloc));
outfit.appendChild(beltelement);
}
if (dressloc.equals("none")) {
} else {
Element dresselement = doc.createElement("dress");
dresselement.appendChild(doc.createTextNode(dressloc));
outfit.appendChild(dresselement);
}
if (jacketloc.equals("none")) {
} else {
Element jacketelement = doc.createElement("jacket");
jacketelement.appendChild(doc.createTextNode(jacketloc));
outfit.appendChild(jacketelement);
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(
new File(Environment.getExternalStorageDirectory()
+ File.separator + "images" + File.separator
+ "newxml.xml"));
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
hatloc = "none";
shirtloc = "none";
pantloc = "none";
shoeloc = "none";
acc1loc = "none";
acc2loc = "none";
beltloc = "none";
dressloc = "none";
jacketloc = "none";
savename = "none";
}
Everything worked fine until I got to this section below. I think it's the section where the xml file i created gets written. Does anyone know of a way to do this that works in android?
The code breaks with the TransformerFactory, Transformer, DOMSource, StreamResult and TransformerException.
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(
new File(Environment.getExternalStorageDirectory() + File.separator
+ "images" + File.separator + "newxml.xml"));
transformer.transform(source, result);

I think that the Transfomer class is not included in the Android API you're using.
To avoid using Transformer you should manually iterate over your xml tree, otherwise you can rely on some external libraries. You should take a look here.

Related

I want append data at the end of text file .xml . I use textfield to SetTextContent . Now I want add next tag on file xml

private void bt_create_xml(ActionEvent e) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("University");
doc.appendChild(rootElement);
Element staff = doc.createElement("student");
// add staff to root
rootElement.appendChild(staff);
// add xml attribute
staff.setAttribute("rollno", tf_input_id.getText());
Element name = doc.createElement("fullname");
name.setTextContent(tf_input_fullname.getText());
staff.appendChild(name);
Element code = doc.createElement("code");
code.setTextContent(tf_input_code.getText());
staff.appendChild(code);
Element birthday = doc.createElement("birthday");
birthday.setTextContent(tf_input_birth.getText());
staff.appendChild(birthday);
Element department = doc.createElement("department");
department.setTextContent(tf_input_depart.getText());
staff.appendChild(department);
Element address = doc.createElement("address");
address.setTextContent(tf_input_add.getText());
staff.appendChild(address);
try{
writeXml(doc, System.out);
FileOutputStream out=new FileOutputStream("D:\\JAVA\\XML-CUOIKY\\XML.xml");
writeXml(doc,out);
}catch (Exception exx){
exx.printStackTrace();
}
} catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
}
private static void writeXml(Document doc,
OutputStream output)
throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// pretty print
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
}
"I want append data at the end of text file .xml . I use textfield to SetTextContent . Now I want add next tag on file xml"

How to read XML server response in JavaScript?

I work on a web project and at this point I need to pass a hard-coded xml from Java to JavaScript to parse that xml; the problem is that I don't know exactly how to do this. As shown below, my xml is stored in a String variable, so I need to pass this variable to JavaScript.
I'm using tomcat as a server.
Java Code - that creates xml:
#Path("/getXml")
#GET
#Produces(MediaType.TEXT_XML)
#Consumes(MediaType.TEXT_PLAIN)
public String getXml(#Context HttpServletRequest request) throws TransformerConfigurationException, TransformerException{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("news-counts");
document.appendChild(rootElement);
int j=12;
for(int i=1; i<10; i++) {
Element item = document.createElement("item");
rootElement.appendChild(item);
item.setAttribute("count", "" + j);
item.setAttribute("date", "201408" + "0" + i);
j=j+2;
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String xmlOutput = writer.getBuffer().toString().replaceAll("\n|\r", "");
// return Response.status(Status.NOT_ACCEPTABLE).entity("xmlOutput").build();
//System.out.println(xmlOutput);
return xmlOutput;
} catch (ParserConfigurationException ex) {
Logger.getLogger(Searcher.class.getName()).log(Level.SEVERE, null, ex);
} finally {
return null;
}
}
JavaScript code - how I tried to acces the xmlOutput variable
function test() {
var r=new XMLHttpRequest();
r.open("GET", "http://localhost:8080/WebApplication6/tavi/searcher/getXml" , false);
r.send();
var responseText = r.responseText;
alert(responseText);
}
You can easily use Jquery for parsing xml. Heres another one Easy XML Consumption using jQuery. If you prefer pure javascript look at this thread.
Using Jquery:
var xml = $.parseXML("<news-counts><item count=\"1\" date=\"2014-08-13 00:00:00\">Stuff</item><item count=\"2\" date=\"2014-08-13 01:01:01\">Bar</item></news-counts>");
var x = xml.getElementsByTagName('item');
for(i=0;i<x.length;i++)
{
console.log(x.item(i).textContent); //Stuff Bar
console.log(x.item(i).getAttribute('count')); //1 2
console.log(x.item(i).getAttribute('date')); //2014-08-13 00:00:00 2014-08-13 01:01:01
}
Using javascript:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
var xml = parseXml("<news-counts><item count=\"1\" date='2014-08-13 00:00:00'>Stuff</item><item count=\"2\" date='2014-08-13 00:00:00'>Bar</item></news-counts>");//get attributes or contents after this line
You can parse your xml in javascript by this way -
var content = xml_string;//your xml string variable
if (typeof content == 'string') {
content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
}
You can parse xml by jQuery. Ref: http://www.jquerybyexample.net/2012/04/read-and-process-xml-using-jquery-ajax.html

Java read XML and put textnodes into an array of strings?

I apologize if this question has been asked somewhere, I've been searching on google for over an hour and can't seem to figure out how to do this.
I've created a config file for an application I'm making which is stored in XML and I've gotten the application to successfully create the XML file if it doesn't exist using DOM,
(code,in case it's needed)
public static void newConfig() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("settings");
doc.appendChild(rootElement);
// address element
Element address = doc.createElement("address");
address.appendChild(doc.createTextNode("127.0.0.1"));
rootElement.appendChild(address);
// port element
Element port = doc.createElement("port");
port.appendChild(doc.createTextNode("3306"));
rootElement.appendChild(port);
// user element
Element user = doc.createElement("user");
user.appendChild(doc.createTextNode("user"));
rootElement.appendChild(address);
// password element
Element pass = doc.createElement("pass");
pass.appendChild(doc.createTextNode("password"));
rootElement.appendChild(pass);
// database element
Element datab = doc.createElement("database");
datab.appendChild(doc.createTextNode("A1"));
rootElement.appendChild(datab);
// write the content to XML
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("config.xml"));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
which creates this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<settings>
<port>3306</port>
<address>127.0.0.1</address>
<pass>password</pass>
<database>A1</database>
</settings>
how would I go about retrieving those textnodes as an array of strings?
try this
NodeList nodes = docBuilder.parse(new File("1.xml")).getDocumentElement().getChildNodes();
String[] a = new String[4];
for (int i = 0, j = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if (n instanceof Element) {
a[j++] = n.getTextContent().trim();
}
}

Write xml using Java for Multiple Records

How to write xml for Multiple records ?
Desired output
<Root>
<Header>
<HeaderTag>Table of Contents</HeaderTag>
<HeaderRow>
<Content>1.Intoduction</Content>
</HeaderRow>
<HeaderRow>
<Content>2.Basics</Content>
</HeaderRow>
</Header>
</Root>
Need looping or iterator for Header Row to accomodate rows for content as mentioned above.
Appreciate your help.
Using below piece of code
public void createRuleXML() {
try {
String newXmlPath = "C:\\write\\CreatedRuleXml.xml";
DocumentBuilderFactory documentFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder =
documentFactory.newDocumentBuilder();
// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Root");
document.appendChild(rootElement);
// define school elements
Element TocHeader = document.createElement("Header");
rootElement.appendChild(TocHeader);
Element HeaderTag = document.createElement("HeaderTag");
HeaderTag.appendChild(document.createTextNode("Table Of Contents"));
TocHeader.appendChild(HeaderTag);
Element TocHeaderRow = document.createElement("HeaderRow");
TocHeader.appendChild(TocHeaderRow);
Element Content = document.createElement("Content");
Content.appendChild(document.createTextNode("1.Introduction"));
TocHeaderRow.appendChild(Content);
Content.appendChild(document.createTextNode("2.Basics"));
TocHeaderRow.appendChild(Content);
However its is returning
Table Of Contents1.Introduction2.Basics
Got fix with below piece of code.
public void createRuleXML() {
try {
String newXmlPath = "C:\\docwrite\\CreatedRuleXml.xml";
DocumentBuilderFactory documentFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentFactory
.newDocumentBuilder();
// define root elements
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Root");
document.appendChild(rootElement);
// define school elements
Element TocHeader = document.createElement("Header");
rootElement.appendChild(TocHeader);
Element HeaderTag = document.createElement("HeaderTag");
HeaderTag.appendChild(document.createTextNode("Table Of Contents"));
TocHeader.appendChild(HeaderTag);
TocHeader.appendChild(getToc(document, "1.Introduction"));
TocHeader.appendChild(getToc(document, "2.Basics"));
// creating and writing to xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource domSource = new DOMSource(document);
StreamResult streamResult = new StreamResult(new File(newXmlPath));
transformer.transform(domSource, streamResult);
System.out.println("File saved to specified path!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
private static Node getToc(Document doc, String tocContent) {
Element tocHeaderRow = doc.createElement("HeaderRow");
//create name element
tocHeaderRow.appendChild(getDetailElements(doc, tocHeaderRow, "Content", tocContent));
return tocHeaderRow;
}
//utility method to create text node
private static Node getDetailElements(Document doc, Element element, String name, String value) {
Element node = doc.createElement(name);
node.appendChild(doc.createTextNode(value));
return node;
}

Java XML: IndexOutOfBoundsException When appending a node

Now that I am writing a messenger program. The following code shall store the message history.
Sadly, I've encountered an "IndexOutOfBounds" exception on a line and I've been trying for a whole day,
but still can't figure out the problem.
So here it is.
public static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final String FILE_PATH = "/data/data/com.demo.xmppchat/";
public static Map<Date, String> messagesMap = new TreeMap<Date, String>();
// File should be saved as /username/buddy.xml
public static void writeHistory(String username, String buddy, Map<Date, String> messages)
{
try {
// Check if the file exists. If the file does not exist, create and initiate one.
File file = new File(FILE_PATH + username);
if (!file.exists()) {
file.mkdirs();
}
file = new File(FILE_PATH + username + "/" + buddy + ".xml");
// file.setReadable(true); file.setWritable(true); file.setExecutable(true);
if (!file.exists()) {
file.createNewFile();
initiateHistoryFile(username, buddy);
}
// Now that the XML file should exists as we have created and initialized one.
// TODO:
// Now we modify the XML file
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
Element root = doc.getDocumentElement();
Element rootE = doc.getDocumentElement();
String s = "";
Node n = null;
for (Map.Entry<Date, String> entry : messages.entrySet()) {
// <message>
Element messageE = doc.createElement("message");
rootE.appendChild(messageE);
// Set attribute to <message> element
// messageE.setAttribute("id", "1");
// <from>
Element fromE = doc.createElement("from");
fromE.appendChild(doc.createTextNode(buddy));
messageE.appendChild(fromE);
// <date>
Element dateE = doc.createElement("date");
s = SDF.format(entry.getKey());
n = doc.createTextNode(s);
dateE.appendChild(n);
messageE.appendChild(dateE);
// <text>
Element textE = doc.createElement("text");
s = entry.getValue();
n = doc.createTextNode(s);
textE.appendChild(n);
messageE.appendChild(textE);
root.appendChild(messageE); // <- *** THIS IS WHERE "IndexOutOfBounds" exception OCCURS! ***
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
// Write the file
// FileWriter fileWritter = new FileWriter(file.getName(),true);
// BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
// bufferWritter.write("");
// bufferWritter.close();
} catch (Exception e) {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_SYSTEM, ToneGenerator.MAX_VOLUME);
toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
e.printStackTrace();
}
}
The Log:
W/System.err(1067): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 W/System.err(1067): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) W/System.err(1067): at java.util.ArrayList.add(ArrayList.java:143) W/System.err(1067): at org.apache.harmony.xml.dom.InnerNodeImpl.insertChildAt(InnerNodeImpl.java:126) W/System.err(1067): at org.apache.harmony.xml.dom.InnerNodeImpl.appendChild(InnerNodeImpl.java:52) W/System.err(1067): at com.demo.xmppchat.XMLReadWrite.writeHistory(XMLReadWrite.java:113)

Categories