How to get String content of Document object(including markup)? - android

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
//here append some children....
(this application should run on andoroid API 4)
the problem is : how can I get the text content(including markup) of the "doc" ?
I will appreciated if someone can give me some advice. Thanks~!

TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(d), new StreamResult(sw));
System.out.println(sw.toString());

Related

How to get properly indented XML on Android?

Based on several examples here on StackOverflow I have the following code for indenting XML.
I have a source xml file in a String. Output however is not indented, but it also doesn't give any errors. Output is checked in the debugger, and doesn't contain any characters like spaces or tabs, that could be rendered wrongly and thus overlooked.
String input = "xmldata";
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
return stringWriter.toString();
I have also tried setting indent-amount to "2", but then the app would complain about a unknown attribute. Probably this is not implemented in Android.
Am I doing something wrong here? Are there other options for generating a indented xml file from a source xml string?
You can try something like this:
String input = "xmldata";
InputSource is = new InputSource(new StringReader(input));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(is);
System.out.println(prettyPrint(doc));
public static final String prettyPrint(Node xml) throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {
StringWriter stringWriter = new StringWriter();
StreamResult out = new StreamResult(stringWriter);
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(xml), out);
return out.getWriter().toString();
}

IO Exception looking for File Path using DOM in android

There are a few posts re: this topic but can't figure out why this won't work.
Keep getting an IOException. Guessing it can't find the file. Cheers.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("//res/xml/xml_data.xml");
Change yours with this
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("res/xml/xml_data.xml");
Your URL is incorrect. Resources take the form:
"android.resource://[package]/[res type]/[res name]"
or
"android.resource://[package]/[res id]
ie
"android.resource://com.org.example/xml/xml_data" // No extension
"android.resource://com.org.example/" + R.xml.xml_data

XML values not change after use setNodesValue

I would like to change the values of RouteName node, according to the below code, I have studied some tutorials and applied it. Am I on the right way? what did I miss?
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(Environment.getExternalStorageDirectory()+"/Trip/"+tripID+".trip"));
Node nodes = doc.getElementsByTagName("RouteName").item(0);
//newname is String variable which retrive value from edite text box
nodes.setNodeValue(newname);
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(Environment.getExternalStorageDirectory()+"/Trip/"+tripID+".trip"));
transformer.transform(source, result);
}
catch (Exception e) {
e.printStackTrace();
}
you are writing/setting new value to dom object, which is not a physical file/document, if you want to reflect the changes to the filesystem, you need to write new contents on FileOutputStream.

Parsing XML file stored in internal storage using DOM parser in android.

I have created an xml file in the device's internal storage as described on the android developers website. I now want to parse the file using DOM parser. What do i need to do to make the DOM parser read my XML file??
Here's a snippet:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new InputSource(new StringReader(data)));
dom.getDocumentElement().normalize();
What do i need to put in the place of "data" in:
Document dom = db.parse(new InputSource(new StringReader(data)));
I know it's silly but any help would be appreciated.
You can make a input stream of the xml string like below and then getting nodes you can parse to get values.
InputStream is = new ByteArrayInputStream(theXMLString.getBytes("UTF-8"));
// Build XML document
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
Remember you are passing xml file as a string.
You can give FileInputStream in inputsource
Document dom = db.parse(new InputSource(new FileInputStream(data)));
For reading XML file, you should try below
FileInputStream in = new FileInputStream("/sdcard/text.txt");
StringBuffer data = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
String finalData =data.toString(); // Here is your data.
Hope above may useful to you.
Try this code for parsing from Asset folder using DOM Parser :
DocumentBuilderFactory DBF;
DocumentBuilder DB;
Document dom;
Element elt;
DBF = DocumentBuilderFactory.newInstance();
DB = DBF.newDocumentBuilder();
dom = DB.parse(new InputSource(getAssets().open("city.xml")));
elt = dom.getDocumentElement();
NodeList items = elt.getElementsByTagName("item");
where item is Node element, add try ctch block as per the requirements.

XML String parsing in Android?

I use the following code to parse the XML file.
DocumentBuilderFactory factory;
DocumentBuilder builder;
InputStream is;
Document dom;
try {
factory = DocumentBuilderFactory.newInstance();
is = new FileInputStream(strFileName);
builder = factory.newDocumentBuilder();
dom = builder.parse(is);
}
catch(Exception e){}
Instead of XML file is there any way to parse the String.
String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>";
You can convert your string to an InputStream using ByteArrayInputStream:
String xml ="valid xml here";
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
dom = builder.parse(is);
You can use StringReader :
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document d = builder.parse(is);

Categories

Resources