i would like modify text of xml tag value i have used an xml as follows
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
here i would like to change the from name Jani as prasad.how can i chage that by using java code
i have written a java code as follows
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("/mnt/sdcard/one.xml"));
//Get the staff element by tag name directly
Node nodes = doc.getElementsByTagName("note").item(0);
//loop the staff child node
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
//get the salary element, and update the value
if("from".equals(nodes.getNodeName())){
node.setNodeValue("prasad");
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/mnt/sdcard/one.xml"));
transformer.transform(source, result);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
There is problem in your code: "Jani" is a text node with parent element node "from". So you should change value of the text node.
...
for (int i =0; i<list.getLength();i++) {
Node node = list.item(i);
//get the salary element, and update the value
if("from".equals(node.getNodeName())){
Text text = (Text) ((Element) node).getChildNodes().item(0);
text.setNodeValue("prasad");
}
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/mnt/sdcard/one.xml"));
transformer.transform(source, result);
...
And I think RegExp would be much easier for this task
"your xml as string".replaceAll("<from>.*?</from>", "<from>prasad</from>");
There are several different examples available.
Writing XML on Android This seems to have the best samples.
Other hits:
How to rewrite or modify XML in android 2.1 version
Load and modify xml file in Android
Related
I am new to Android. I have been trying to update a node value of my xml file using DomParser. I have been workin with asset folder xml file to read. I realised asset folder files cannot be updated and then created a raw folder to save my xml file.I have been refering many answers provided by different people for a long time but nothing is workin!
Portion of my .xml file
<events>
<type>ABC</type>
<time>1:30-2:45pm</time>
<day>XYX</day>
<note>123</note>
</events>
and I have been trying the code
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
InputStream is = this.getResources().openRawResource(temp1);
Document doc = docBuilder.parse(is);
if (null != doc.getDocumentElement()){
v1.setText("\n\nhiii888",doc.getDocumentElement()); ("HERE")
RelativeLayout layout = (RelativeLayout) findViewById(R.id.content);
layout.addView(v1);
}
Node nodes = doc.getElementsByTagName("events").item(0);
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
if("type".equals(nodes.getNodeName())){
node.setNodeValue("ABC123");
}
}
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("temp1.xml"));
transformer.transform(source, result);
}
My app shows stopped running when executing this and so I put in the piece of if block with textview and relative layout("mentioned as "HERE") to see where until the code works fine..The getDocumentElement()does return a value and so it displays in textview as
hiii888org.apache.harmony.xml.dom.ElementImpl#e58aa2f
I dont know why this is coming.I also used Text to typecast and retrieve the result and also .toString() function expecting typecasting can solve the problem.Nothing seem to work..Have been trying Xml update now for days...Hope to see answers that can sort my issue regarding xml update other than the already existing ones...Thanks in advance.
InputStream is = openHTTPConnection("blahblah");
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc = null;
try {
builder = fac.newDocumentBuilder();
doc = builder.parse(is);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
doc.getDocumentElement().normalize();
NodeList parentNodes = doc.getElementsByTagName("Parent");
for (int i = 0; i < parentNodes.getLength(); i++){
Node itemNode = parentNodes.item(i);
if (itemNode.getNodeType() == Node.ELEMENT_NODE){
Element parentElement = (Element) itemNode;
NodeList childNodes = ??????
}
}
My XML file:
<Blah>
<Parent>
<Child>
...
</Child>
</Parent>
</Blah>
How can I get the sub element of Parent? The tutorial says NodeList childNodes = (parentElement).getElementsByTagName("Child"); But it does not make sense to me.
It looks like my post is mostly code; But I don't know what to add
Tutorial is correct. This is how you get it:
NodeList childNodes = (parentElement).getElementsByTagName("Child");
Element childElement=(Element)childNodes.item[0];
In case , there are multiple <child> nodes, you can loop through the iterator
In this way you can get sub elements of an xml in android
You could write a xsl
<xsl:template match="/">
<xsl:for-each select="section">
<xsl:value-of select="concat('link ',photo#id, ' from ',#name,' is ',photo#ilink)"><xsl:value-of>
</xsl:for-each>
</xsl:template>
run the xsl on your xml, the output will be link 1 from section1 is ImageLink 1 .. link 4 from section2 is ImageLink 2
I am new developer in java application. I would like to modify an XML file node value. I have used an xml file for modify as follows
<staff id="2">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>2000000</salary>
<age>28</age>
</staff>
in above xml I would like to change salary value as 345375. For this modification I have written code as follows
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("/sdcard/myxml.xml"));
//Get the staff element by tag name directly
Node nodes = doc.getElementsByTagName("staff").item(0);
//loop the staff child node
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
//get the salary element, and update the value
if("salary".equals(node.getNodeName())){
node.setNodeValue("345375");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if I use this way that value not modifying salary.
How can I modify an XML node value?
First you have to realize that node.setValue() is modifying the representation that is stored in memory. Knowing that, then you just need to figure out how to write that output to disk. See this, for an example.
node.Text = "Enter your value here"; //This will work
I am parsing a xml from an url.The url is has mobile IMEI no and searchstring based on my application. i put my xml parsing code in android project it does not work. but if i run as separate java program it is working. please help me.
Log.e("rsport-", "function1");
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setCoalescing(true); // Convert CDATA to Text nodes
factory.setNamespaceAware(false); // No namespaces: this is default
factory.setValidating(false); // Don't validate DTD: also default
DocumentBuilder parser = factory.newDocumentBuilder();
Log.e("rsport-", "function2");
Document document = parser.parse("http://demo.greatinnovus.com/restingspot/search?userid=xxxxxxxxxxxxxxxx&firstname=a&lastname=a");
Log.e("rsport-","function3");
NodeList sections = document.getElementsByTagName("Searchdata");
int numSections = sections.getLength();
for (int i = 0; i < numSections; i++)
{
Element section = (Element) sections.item(i);
if(section.hasChildNodes()==true){
NodeList section1=section.getChildNodes();
for(int j=0;j<section1.getLength();j++){
if(section1.item(j).hasChildNodes()==true) {
for(int k=0;k<section1.item(j).getChildNodes().getLength();k++)
xmlvalue=String.valueOf(section1.item(j).getChildNodes().item(k).getNodeValue()).trim();
arl.add(xmlvalue);
}
}
}
}
}
}
catch(Exception e){}
System.out.println("id"+id+" searchdatacount"+searchdatacount);
System.out.println("---------");
ListIterator<String> litr = arl.listIterator();
while (litr.hasNext()) {
String element = litr.next();
Log.e("rsport-", "elememt");
}
after the Log.e("rsport-", "function2"); does not work.
Refer my blog, i had gave Detailed explanation, http://sankarganesh-info-exchange.blogspot.com/2011/04/parsing-data-from-internet-and-creating.html, and make sure , that you had add the Internet permission in your Manifest file.
If you had gone through Myblog, then you will able to notice that you did the following line as wrong
Document document = parser.parse("http://demo.greatinnovus.com/restingspot/search?userid=xxxxxxxxxxxxxxxx&firstname=a&lastname=a");
use like this
URL url =new URL("http://demo.greatinnovus.com/restingspot/search?userid=xxxxxxxxxxxxxxxx&firstname=a&lastname=a");
Document document= parser.parse(new InputSource(url.openStream()));
I created an XML document using Java in my android application. I have to call a web service in my application and pass this XML as an argument there. But my problem is there created a white space between each tag in the XML.
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element root = doc.createElement("subscriber");
doc.appendChild(root);
//creating child node for username
EditText txtusername=(EditText)findViewById(R.id.txtUserName);
subscriber[0]=String.valueOf(txtusername.getText());
Element UserName=doc.createElement("UserName");
UserName.setTextContent(subscriber[0]);
root.appendChild(UserName);
//creating child node for PASSWORD
EditText txtPassword=(EditText)findViewById(R.id.txtPassword);
subscriber[1]=String.valueOf(txtPassword.getText());
Element Password=doc.createElement("Password");
Password.setTextContent(subscriber[1]);
root.appendChild(Password);
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString =sw.toString();
url = new URL("http://192.168.70.14/NewsLetter/subscribing.php?register= " + xmlString);
conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "text/xml; charset=UTF-8");
dis = conn.getInputStream();
The XML is:
<subscriber> <UserName>miya</UserName> <Password>today</Password> </subscriber>
Please give the solution for how to remove the white spaces between the UserName and Password tags.
Of course, it depends on your XML itself. However, you could try using regular expressions.
As an example:
yourXmlAsString.replaceAll(">[\\s\r\n]*<", "><");
Would remove all whitespace between every XML element.
Method documentBuilderFactory.setIgnoringElementContentWhitespace() controls whitespace creation. Use this before you create a DocumentBuilder.
dbfac.setIgnoringElementContentWhitespace(true);
I was able to remove whitespace/tabs/newlines from my transformation using the following property:
transformer.setOutputProperty(OutputKeys.INDENT, "no");
You had it set to yes. I'm sure this question is old enough that it doesn't matter now; but if anyone runs into this in the future, setting the property to no saved me.
This is the regular expression (?:>)(\s*)<
When you use it in the code for Java use
"(?:>)(\\s*)<" and replace with "><"
String xmlString = "<note> <to>Tove</to> <from>Jani</from <heading>Reminder</heading> <title>Today</title> <body>Don't forget me this weekend!</body> </note>";
String str = xmlString.replaceAll("(?:>)(\\s*)<", "><");
This will remove the spaces between the tags and maintain the spaces for the value.
Input:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading> <title>Today</title>
<body>Don't forget me this weekend!</body>
</note>
Output:
<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><title>Today</title><body>Don't forget me this weekend!</body></note>
None of the other answers worked for me. I had to use the below code, to remove both additional whitespaces and new lines.
xmlString.trim().replace("\n", "").replaceAll("( *)<", "<")
This worked for me, thank you. As a caveat, although this is actually useful for my purpose, I noticed that it can also remove text content if that consists only of whitespace. For example, running the following:
String xmlIn = "<tag> </tag> <tag>\t</tag>\t <tag>\r\n</tag><tag> text </tag>";
String xmlOut = xmlIn.replaceAll("(?:>)(\\s*)<", "><");
System.out.println(xmlOut);
gives the following:
<tag></tag><tag></tag><tag></tag><tag> text </tag>
You can create a copy of all nodes in a document, and trims the nodeValue of each node if it exists.
const copyChildrenNodesWithoutWhiteSpace = (document) => {
const clone = document.cloneNode();
for (const child of document.childNodes) {
const childCopy = copyChildrenNodesWithoutWhiteSpace(child);
clone.appendChild(childCopy);
if (childCopy.nodeValue) {
childCopy.nodeValue = childCopy.nodeValue.trim();
}
}
return clone;
};
const result = copyChildrenNodesWithoutWhiteSpace(anyDocument);