I have xml:
<Info>
<info_1/>
<info_2/>
<info_3>
<i ID="1"/>
<i ID="2"/>
<i ID="3"/>
</info_3>
<info_4>
</indo_4>
</Info>
I need to delete a specific node in info_3, for example a node in which ID = 1, how can I do this?
I tried to do this, but log shows before and after length = 3 :
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Node node=nList.item(1);
node.getParentNode().removeChild(node);
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Solution that helped me:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(bb)));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Set<Element> targetElements = new HashSet<>();
for (int i = 0; i < nList_Loan_guarantor.getLength(); i++) {
Element e = (Element)nList_Loan_guarantor.item(i);
if ("10938".equals(e.getAttribute("ID"))) {
targetElements.add(e);
}
}
for (Element e: targetElements) {
e.getParentNode().removeChild(e);
}
doc.getDocumentElement().normalize();
NodeList nList_2 = doc.getElementsByTagName("i");
Log.e("LOG", "nList.getLength() = " + nList.getLength());
Related
Here is My xml document iam trying to prase it using DOMXmlParser..
< records>
<employee>
<name>Sachin Kumar</name>
<salary>50000</salary>
</employee>
<employee>
<name>Rahul Kumar</name>
<salary>60000</salary>
</employee>
<employee>
<name>John Mike</name>
<salary>70000</salary>
</employee>
< /records>
Following is Code in OnCreate.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("employee");
System.out.println("No Of Collected Objects" + nList.getLength() );
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\n\nFirstName : "
+ getValue("firstname",element2) + "\n");
tv1.setText(tv1.getText()+"\n\nMiddleName : "
+ getValue("middlename",element2) + "\n");
tv1.setText(tv1.getText()+"\n\nLastName : "
+ getValue("lastname",element2) + "\n");
tv1.setText(tv1.getText() + "Salary : "
+ getValue("salary",element2) + "\n");
tv1.setText(tv1.getText() + "-----------------------");
}
}
}
Can anyone tell what is the use of getChildNodes in following code and why the item index should always be 0 ??.
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
getChildNotes retrieves a list of all child nodes of the first element with "tag".
Then node is assigned the first element in the returned list.
I want to parse "ALışVERIş" type of content from service.
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
URL _url = new URL(params[0]);
xr.parse(new InputSource(_url.openStream()));
What I tried DOM Parser instead of XaxParser. Check below function and call it inside background thread :
public String readXML(){
StringBuilder stringBuilder = new StringBuilder();
try {
URL _url = new URL("http://182.160.161.2/~siva/turkish/web_serv/category.php?order_by=desc&category_id=2");
File fXmlFile = new File(new InputSource(_url.openStream()).getByteStream().toString());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(_url.openStream()).getByteStream());
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("document");
Node nResp = nList.item(0);
Element fstElmnt = (Element) nResp;
NodeList nameList1 = fstElmnt.getElementsByTagName("response");
Node mCat = nameList1.item(0);
Element catElmt = (Element) mCat;
NodeList catList = catElmt.getElementsByTagName("category");
System.out.println("----------------------------");
for (int temp = 0; temp < catList.getLength(); temp++) {
Node nNode = catList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
stringBuilder.append("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent()+"\n");
stringBuilder.append("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
System.out.println("Category ID : " + eElement.getElementsByTagName("category_name").item(0).getTextContent());
System.out.println("Category Name : " + eElement.getElementsByTagName("category_id").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Here is a screenshot of my device, Have a look :
You can see those turkish language too :)
Here is my code. I want to see these parsed strings into ListView in Android. How can I do this?
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
System.out.println("Name: " + getCharacterDataFromElement(line));
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}
I have one local xml file. I am storing here : res/xml/myxml.xml
<?xml version="1.0" encoding="utf-8"?>
<list>
<lists>
<tag>College Website</tag>
<value>http://www.nitk.ac.in/</value>
<lastupdate>04-07-2012</lastupdate>
</lists>
<lists>
<tag>College Images</tag>
<value>http://studentsworld.nitk.ac.in/index.php?q=convocation.html</value>
<lastupdate>25-9-2011</lastupdate>
</lists>
</list>
I have doc for loop. but how to connect local xml file in doc parser. i don't want url model, i want to a local xml file.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
tag[i] = new TextView(this);
value[i] = new TextView(this);
lastupdate[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tag");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
tag[i].setText("tag = " + ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("value");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
value[i].setText("value = " + ((Node) websiteList.item(0)).getNodeValue());
NodeList lastupdateList = fstElmnt.getElementsByTagName("tag");
Element lastupdateElement = (Element) lastupdateList.item(0);
lastupdateList = lastupdateElement.getChildNodes();
lastupdate[i].setText("lastupdate = " + ((Node) lastupdateList.item(0)).getNodeValue());
layout.addView(tag[i]);
layout.addView(value[i]);
layout.addView(lastupdate[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
I have main.xml file
please send me a code
put you XML file in assets folder and try this
InputStream raw = getApplicationContext().getAssets().open("simple.xml");
and try this
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(raw);
....
...
put you XML file in assets folder and Try this way
String xml;
Document doc;
try{
xml=getXML(getAssets().open("yourxmlfilename.xml"));
}catch(Exception e){
Log.d("Error",e.toString());
}
doc = XMLfromString(xml);
where getXML and XMLfromString method are as shown below
//getXML method
public static String getXML(InputStream is)throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
//XMLfromString method
public final static Document XMLfromString(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) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
please use below code for parse local xml,
InputStream in = this.getResources().openRawResource(R.raw.xmlfile);
And then parse inputstream,
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
Document document = db.parse(in, null);
I am having some trouble parsing XML in Android from an URL. I don't know if it's the XML parsing that's the problem or only when I am trying to show it on the screen because
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this, android.R.layout.simple_list_item_1, stopNumbers));
wont show anything. The code below works perfectly in a java program.
URL: http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0
try {
ArrayList<Double> xCords = new ArrayList<Double>();
ArrayList<Double> yCords = new ArrayList<Double>();
ArrayList<String> stopNumbers = new ArrayList<String>();
ArrayList<String> bussLocations = new ArrayList<String>();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder
.parse(new URL(
"http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0")
.openStream());
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfObjects = doc.getElementsByTagName("iGNMObject");
for (int s = 0; s < listOfObjects.getLength(); s++) {
Node firstPersonNode = listOfObjects.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList stopNumList = firstPersonElement
.getElementsByTagName("StopNumber");
Element ageElement = (Element) stopNumList.item(0);
if (ageElement != null) {
NodeList textAgeList = ageElement.getChildNodes();
String stop = ((Node) textAgeList.item(0))
.getNodeValue().trim();
stopNumbers.add(stop);
// ------
// -------
NodeList xPosList = firstPersonElement
.getElementsByTagName("XPosition");
Element firstNameElement = (Element) xPosList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
String temp2 = ((Node) textFNList.item(0))
.getNodeValue().trim();
double x = Double.parseDouble(temp2);
xCords.add(x);
// -------
NodeList yPosList = firstPersonElement
.getElementsByTagName("YPosition");
Element lastNameElement = (Element) yPosList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
String temp3 = ((Node) textLNList.item(0))
.getNodeValue().trim();
double y = Double.parseDouble(temp3);
yCords.add(y);
// ----
NodeList stopAkaList = firstPersonElement
.getElementsByTagName("StopAka");
Element stopAka = (Element) stopAkaList.item(0);
NodeList textStopAKAList = stopAka.getChildNodes();
String plats = ((Node) textStopAKAList.item(0))
.getNodeValue().trim();
bussLocations.add(plats);
} else {
}
}// end of if clause
}// end of for loop with s var
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this,
android.R.layout.simple_list_item_1, stopNumbers));
} catch (Exception e) {
}
}
}
}
Solved it. I had forgot to add internet permission in the manifest.