Android xml parsing based on selection of item [duplicate] - java

Hi i want to parse XML and display list based on selection of user
my xml is looking like this
below is my code
try {
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("company");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
// creating new HashMap
Element e = (Element) n1.item(i);
System.out.println("name node "+parser.getValue(e, "name"));
}
by this way i am getting the output like
Company ABC
Company XYZ
of Companies list
but
i would write code like
NodeList n1 = doc.getElementsByTagName("province");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
// creating new HashMap
Element e = (Element) n1.item(i);
System.out.println("name node "+parser.getValue(e, "name"));
}
i am getting list of province name
Alberta
Ontario
New York
Florida
but it should work like this
when i select Company ABC
only two provision list should display
Alberta
Ontario
not should all display can any body help me how to rewrite my code

This should do it:
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("company");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
Element e = (Element) n1.item(i);
System.out.println("name node " +parser.getValue(e, "name"));
NodeList children = e.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeName().equalsIgnoreCase("province")) {
System.out.println("name node " + parser.getValue((Element)child, "name"));
}
}
}

Use Node.getChildNodes() over the "company" nodes. Then, to get the child province nodes, compare by name. Example:
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList n1 = doc.getElementsByTagName("company");
// looping through all item nodes <item>
for (int i = 0; i < n1.getLength(); i++) {
Node companyNode = n1.item(i);
NodeList childNodes = companyNode.getChildNodes();
// Here we're getting child nodes inside the company node.
// Only direct childs will be returned (name and province)
for (int j = 0; j < childNodes.getLength(); j++) {
Node childNode = childNodes.item(j);
if("province".equalsIgnoreCase(childNode.getName())){
//Do something with province
}
}
}

Try the following code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView category[];
try {
URL url = new URL(
"http://xyz.com/aa.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
/** Assign textview array lenght by arraylist size */
name = new TextView[nodeList.getLength()];
website = new TextView[nodeList.getLength()];
category = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Set the layout view to display */
setContentView(layout);
}
}

The getElementsBytagName called on the document object will always return the list of all the nodes with the given tag name in the whole document. Instead, filter out the single company element you are interested in, and then call getElementsByTagName on it. E.g.
Element companyEl = doc.getElementById(desiredCompanyId);
if (companyEl != null) { // always good to check
NodeList n1 = companyEl.getElementsByTagName("province");
// your code here
}

Try with this code
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
name[i] = new TextView(this);
website[i] = new TextView(this);
category[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
name[i].setText("Name = "
+ ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("website");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
website[i].setText("Website = "
+ ((Node) websiteList.item(0)).getNodeValue());
category[i].setText("Website Category = "
+ websiteElement.getAttribute("category"));
layout.addView(name[i]);
layout.addView(website[i]);
layout.addView(category[i]);
}

Related

Java XML removeChild not working?

Hello so i've looked this question up alot but I couldn't find a solution that worked. I'm basically trying to remove the "job" node as seen declared in line 7 and removed in line 13. There's 0 runtime errors but the node doesn't get removed.
NodeList rootNodes = xml.getElementsByTagName("jobs");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList jobsList = rootElement.getElementsByTagName("job");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
if(jobElement.getAttribute("id").equals(
msgEvent.getMessage().getContentRaw().split(" ")[2]))
{
rootNode.removeChild(job);
msgEvent.getChannel().sendMessage("Removed Job " + jobElement.getAttribute("id") + " (Summary: '" + jobElement.getAttribute("summary") + "')").complete();
}
}
Here's the XML
<?xml version = "1.0"?>
<jobs>
<job payment = "50000" poster="171048434529337344" collect = "asdf" id = "1" summary="asdfd" expires="5/10/18"> </job>
<job payment = "10000" poster="171048434529337344" collect = "asdf" id = "2" summary="asdf" expires="5/10/18"> </job>
</jobs>
since this is too large for comment, Here is my test code and results:
public static void main(String[] args) {
try (InputStream is = Files.newInputStream(Paths.get("C://Temp/xx.xml"))) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document xml = builder.parse(new InputSource(is));
NodeList rootNodes = xml.getElementsByTagName("jobs");
Node rootNode = rootNodes.item(0);
Element rootElement = (Element) rootNode;
NodeList jobsList = rootElement.getElementsByTagName("job");
System.out.println("list before removal");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
System.out.println(jobElement.getAttribute("id"));
}
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
if (jobElement.getAttribute("id").equals("1")) {
rootNode.removeChild(job);
}
}
System.out.println("list after removal");
jobsList = rootElement.getElementsByTagName("job");
for (int i = 0; i < jobsList.getLength(); i++) {
Node job = jobsList.item(i);
Element jobElement = (Element) job;
System.out.println(jobElement.getAttribute("id"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
output:
list before removal
1
2
list after removal
2

XML parsing to Java - getting root attribute value

I'm having a slight problem with XML parsing.
I'm creating a function where the parameter is a certain "element" from the XML file.
When found, I want to return the value of the root attribute.
Here's my code:
FileInputStream file = new FileInputStream(new File("C:\\Users\\Grizzly\\Java\\Projet_16_17-20161214\\bdd.xml"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("type");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if(nNode.toString().equalsIgnoreCase(element))
{
Element eElement = (Element) nNode;
System.out.println("Taxe= "+ eElement.getAttribute("taxe"));
}
}
}
Any idea on how to do this?
Here's my XML file:
<?xml version="1.0"?>
-<types>
-<type id="Nourriture" taxe="0.1">
<element>pomme</element>
<element>fraise</element>
<element>fromage</element>
<element>viande rouge </element>
</type>
-<type id="Matiere Premiere" taxe="0.2">
<element>fer</element>
<element>polypropylene</element>
</type>
-<type id="Element Solide" taxe="0.3">
<element>voiture</element>
<element>planche surf</element>
<element>pistolet</element>
</type>
</types>
In my code, I tried to get the elements of a certain node from the nodelist and then compare it to the the string "element" which is the input of the user, and if they match it will check the attribute value of taxe linked to it.
Thanks in advance.
EDIT: I'm getting closer to what I need:
NodeList nList = doc.getElementsByTagName("type");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
NodeList nChildren = nNode.getChildNodes();
Element eElement = (Element) nNode;
for(int i = 0; i < nChildren.getLength(); i++)
{
String onElement = eElement.getElementsByTagName("element").item(i).getTextContent();
if(onElement.equalsIgnoreCase(element))
{
System.out.println("id : " + eElement.getAttribute("id"));
System.out.println("taxe : " + eElement.getAttribute("taxe"));
break;
}
}
}
But it's only reading the first element... and item(i) isn't working.
Any idea?
If I understand you correctly, you are trying to fetch specific attributes (id and taxe) of all the document nodes having at least one child element with specific name (element).
Although the problem can be solved by iterating the DOM and keeping the states, I would rather delegate this task to XPath. A code with XPath will look cleaner and be more maintainable. For example, in order to fetch all elements having attributes id and taxe and a child element element you can use an XPath expression like //*[#id and #taxe element]. The matching nodes are fetched in a single line. You can simply iterate the nodes and collect the attributes as shown in the following example.
Example
public static void main(String args[]) {
String element = args.length > 0 ? args[0] : "element";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
FileInputStream file = new FileInputStream(new File("/some/file.xml"));
Document doc = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//*[#id and #taxe and " + element + "]";
NodeList nodeList = (NodeList) xPath.compile(expression)
.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
NamedNodeMap attributes = node.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node aNode = attributes.item(j);
System.out.printf(
"%s: %s\n",
aNode.getNodeName(),
aNode.getNodeValue()
);
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
Sample Output
id: Nourriture
taxe: 0.1
id: Matiere Premiere
taxe: 0.2
id: Element Solide
taxe: 0.3
Note, the sample above prints all attributes of the parent element. If you want to print only specific ones, you can, obviously, add a trivial check like this:
String aName = aNode.getNodeName();
if (aName.equals("taxe")) { // ...
But you can actually filter out the attributes with XPath:
String expression = "//*[ " + element + "]/#*[name() = 'id' or name() = 'taxe']";
NodeList nodeList = (NodeList) xPath.compile(expression)
.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.printf("%s: %s\n", node.getNodeName(), node.getNodeValue());
}
The XPath expression above fetches all attribute nodes having names equal to whether id, or taxe. If you want all attributes, simply remove the last condition:
String expression = "//*[ " + element + "]/#*";

How to store xml in list in Android studio

TextView Naziv[];
TextView Id[];
int a = 0;
//ovaj primjer sam nasao na netu, treba parsirat XML
//ali nisam siguran da li treba podatke parsirat u ovoj klasi ili u nekoj drugoj
//probaj to skuzit
try{
String address = "http://www.dajsve.com/rss.ashx?svigradovi=1";
URL gradoviXmlUrl = new URL(address);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(gradoviXmlUrl.openStream());
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Grad");
Naziv = new TextView[nodeList.getLength()];
List<Grad> gradoviLista = null;
for(int i=0; i<nodeList.getLength(); i++){
Element element = (Element) nodeList.item(i);
NodeList nazivGrada = element.getElementsByTagName("Naziv");
NodeList idGrada = element.getElementsByTagName("Id");
Element nazivGradaElement = (Element) nazivGrada.item(i);
Element idGradaElement = (Element) idGrada.item(i);
String gradNaziv = nazivGradaElement.getAttribute("Naziv");
/*Grad grad = null;
grad.setNaziv(nazivGrada);
grad.setId(idGradaElement);
gradoviLista.add(idGradaElement, nazivGradaElement);*/
}
a = nodeList.getLength();
//ovdje u varijablu zapisujem broj gradova, koje kasnije koristim samo za provjeru u main aktivitiju
The fetch from web service works, in variable a i store the length of elements, but the storing into variables does'nt work.
Element element = (Element) nodeList.item(i);
NodeList nazivGrada = element.getElementsByTagName("Naziv");
NodeList idGrada = element.getElementsByTagName("Id");
Element nazivGradaElement = (Element) nazivGrada.item(i);
Element idGradaElement = (Element) idGrada.item(i);
String gradNaziv = nazivGradaElement.getAttribute("Naziv");
This code does'nt work.
this is the xml: http://www.dajsve.com/rss.ashx?svigradovi=1
Can somebody help me?
nodeList.item(i); returns the node at the indexth position in the NodeList, a Node is not always an element so you will get a ClassCastException on:
Element element = (Element) nodeList.item(i);
Just make sure to check if(FPN.getNodeType() == Node.ELEMENT_NODE) before casting a Node to an Element
Or you can use:
Node node = nodeList.item(i);
String gradNaziv = getNodeValueByTagName(node ,"Naziv");

how to Parse item and subitem in xml parsing

<taxmann>
<docdetails>
<info id="104010000000007617" date="19780225">
<physicalpath>\\192.168.1.102\CMS\DATA</physicalpath>
<filepath isxml="N">
\NOTIFICATIONS\DIRECTTAXLAWS\HTMLFILES\150025021978.htm
</filepath>
<summary></summary>
<description></description>
<heading>
2187 [S.O.1500] | Section 35(1)(ii) of the Income-tax Act, 1961 - Scientific research expenditure - Approved scientific research associations/institutions
</heading>
<correspondingcitation/>
<hasfile>YES</hasfile>
<sortby>20120328160152743</sortby>
<parentid></parentid>
<parentchapterid></parentchapterid>
</info>
</docdetails>
</taxmann>
Code:
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_DOCDETAILS);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_HEADING, parser.getValue(e, KEY_HEADING));
// adding HashList to ArrayList
menuItems.add(map);
}
This is My Xml Format i want to xmlParse and want to dsiaply id,date,heading i m able to display heading But i am not to print date and id can u please tell me how i will implemnt it . this is my code to Print heading please modify my code and Print heading ,id,date..
1.Declaration
String URL = "http://www.google.co.in/ig/api?news&hl=en";
String KEY_ITEM = "news";
String KEY_ID = "news_entry";
String KEY_NAME = "title";
String KEY_COST = "url";
String KEY_DESC = "snippet";
2.Parsing
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
System.out.println("attrlength"+attributes.getLength());
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
// menuItems.add(map);
}
NodeList nl = doc.getElementsByTagName("info");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}

Java:XML Parsing

I have the xml file as follows,
<CHPkt xmlns="Smartscript/EmarSchema">
<CHInfo>
<StoreId>1800</StoreId>
<CHId>DB439A79-3D6F-4D25-BE0A-C4692978C072</CHId>
<CHName>Test</CHName>
<Address>
<Address1>Test Address</Address1>
</Address>
<DrugRounds>
<RoundTime>09:00</RoundTime>
<RoundTime>13:00</RoundTime>
<RoundTime>17:00</RoundTime>
</DrugRounds>
</CHInfo>
</CHPkt>
How to get the values of the tags which has the same name, my code is as follows,
public class ReadXml {
public static void main(String[] args){
try{
File xmlFile = new File("/home/jayakumar/Desktop/SmartScript.XML");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
NodeList nodeList1 = document.getElementsByTagName("CHInfo");
System.out.println("######################################");
for(int i =0;i<nodeList1.getLength();i++){
org.w3c.dom.Node node = nodeList1.item(i);
if(node.getNodeType()== org.w3c.dom.Node.ELEMENT_NODE){
Element element = (Element) node;
System.out.println("StoreId : " + getTagValue("StoreId", element));
System.out.println("CHId : " + getTagValue("CHId", element));
System.out.println("CHName : " + getTagValue("CHName", element));
System.out.println("Address : " + getTagValue("Address1", element));
}
NodeList nodeList2 = document.getElementsByTagName("DrugRounds");
System.out.println("-------------->"+"DrugRounds");
for(int j =0;j<nodeList2.getLength();j++){
org.w3c.dom.Node subNode = nodeList2 .item(j);
Element e = (Element) subNode;
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static String getTagValue(String sTag, Element element) {
NodeList nlList = element.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
I wasn't able to extract the values of second and third Roudtimes.How to parse the tags with same name
Thanks
Why not just check if it has any child nodes then get the value from it
for (int j = 0; j < nodeList2.getLength(); j++) {
org.w3c.dom.Node subNode = nodeList2.item(j);
NodeList childNodes = subNode.getChildNodes();
for(int iDx = 0; iDx < childNodes.getLength(); iDx++){
if(childNodes.item(iDx) instanceof Element){
Element e = (Element) childNodes.item(iDx);
System.out.println("RoundTime : "+ e.getFirstChild().getNodeValue());
}
}

Categories