I'm trying to write to an XML file, within my XML file I have:
<user>
<name></name>
</user>
And the method I can to write to the XML file:
public void WriteToXML() throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("user");
Node node = nList.item(0);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
if(element2.getTagName() == "name")
{
element2.setNodeValue("SFDSFSDF");
}
}
}
However, the method gets called but for some reason it doesnt actually write to the XML file because when I read it their isn't actually anything within the XML?
Try to replace :
element2.getTagName() == "name"
by :
(element2.getTagName()).equals("name")
Also, try to replace :
element2.setNodeValue("SFDSFSDF");
by :
element2.setTextContent("SFDSFSDF"); //adds content
Related
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 have XML:
<?xml version="1.0" encoding="UTF-8"?>
<categories type="array">
<category>
<category_id>8</category_id>
<category_name>Công Nghệ & Xe</category_name>
<category_code>cong-nghe-xe</category_code>
<subcategory>
<category_id>59</category_id>
<category_name>Kiến trúc - thủ thuật</category_name>
<category_code>cong-nghe-xe_kien-thuc-thu-thuat</category_code>
</subcategory>
.................................................
</category>
.................................................
</categories>
How can I read it and fill ListView in Android, and what should I do : DOM , XML Parser or SAX ??
I prefer DOM for small little snippets like this.
String xml;
Document doc;
Element root = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse( new InputSource( new StringReader( xml ) ) );
root = doc.getDocumentElement();
} catch ( Exception e ) {
// do something
}
if( root != null ) {
NodeList cats = root.getElementsByTagName( "category" );
for( int i=0; i < cats.getLength(); i++ ) {
Element category = (Element)cats.item( i );
....
}
}
Have you tried the example of Android?
http://developer.android.com/training/basics/network-ops/xml.html
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 a Java application which opens an xml file that looks something like this:
<AnimalTree>
<animal>
<mammal>canine</mammal>
<color>blue</color>
</animal>
<!-- ... -->
</AnimalTree>
And I can open it using:
File fXmlFile = getResources.getXml("res/xml/data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList animalNodes = doc.getElementsByTagName("animal");
Then I can simply create a node, push the object into a ListArray, then do what I want with the objects as I loop through the ListArray.
for (int temp = 0; temp < animalNodes.getLength(); temp++) {
Node nNode = animalNodes.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
question thisAnimal = new animal();
thisAnimal.mammal = getTagValue("mammal",eElement);
// ...
Plain and simple! Now only, in Android I cannot simply read the file "res/xml/data.xml" because "File();" requires a String not an integer (id). This is where I am lost. Is there some way I can make "File();" open the file, or is this impossible without using SAXparser or XPP? (both of which I really cannot understand, no matter how hard I try.)
If I am forced to use those methods, can someone show me some simple code analogous to my example?
If it's in the resource tree, it'll get an ID assigned to it, so you can open a stream to it with the openRawResource function:
InputStream is = context.getResources().openRawResource(R.xml.data);
As for working with XML in Android, this link on ibm.com is incredibly thorough.
See Listing 9. DOM-based implementation of feed parser in that link.
Once you have the input stream (above) you can pass it to an instance of DocumentBuilder:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("TheTagYouWant");
Keep in mind, I haven't done this personally -- I'm assuming the code provided by IBM works.
I tried the approach using openRawResource and got a SAXParseException. So, instead, I used getXml to get a XmlPullParser. Then I used next() to step through the parsing events. The actual file is res/xml/dinosaurs.xml.
XmlResourceParser parser = context.getResources().getXml(R.xml.dinosaurs);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT :
Log.v(log_tag, "Start document");
break;
case XmlPullParser.START_TAG :
Log.v(log_tag, "Start tag " + parser.getName() );
break;
case XmlPullParser.END_TAG :
Log.v(log_tag, "End tag " + parser.getName() );
break;
case XmlPullParser.TEXT :
Log.v(log_tag, "Text " + parser.getText() );
break;
default :
Log.e(log_tag, "Unexpected eventType = " + eventType );
}
eventType = parser.next();
}
Try this,
this.getResources().getString(R.xml.test); // returns you the path , in string,invoked on activity object