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");
Related
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 + "]/#*";
Hi I am trying to parse and XML file from an url, my NodeList contains values but getNodeValue for each node returns null. Can anybody help me?
This is my method where I parse the xml.
public ArrayList xmloku(String url) {
ArrayList xmllistesi = new ArrayList();
try {
URL xmlyolu = new URL(url);
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(xmlyolu
.openStream()));
document.getDocumentElement().normalize();
NodeList nodeListCountry = document
.getElementsByTagName("karikatur");
for (int i = konum; i < nodeListCountry.getLength(); i++) {
Node node = nodeListCountry.item(i);
Element elementMain = (Element) node;
xmllistesi.add(elementMain.getNodeValue());
}
Instead of getNodeValue() try using getTextContent()
for (int i = konum; i < nodeListCountry.getLength(); i++) {
Node node = nodeListCountry.item(i);
Element elementMain = (Element) node;
xmllistesi.add(elementMain.getTextContent());
}
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]);
}
I am currently parsing XML, but im not quite sure how to parse the "status" attribute of "message":
<message status="test"> <text>sometext</text> <msisdn>stuff</msisdn> </message>
Here is the code, i have cut off everything unnecessary:
NodeList nodeLst = doc.getElementsByTagName("message");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList numberNmElmntLst = fstElmnt
.getElementsByTagName("msisdn");
Element numberNmElmnt = (Element) numberNmElmntLst.item(0);
NodeList numberNm = numberNmElmnt.getChildNodes();
String phoneNumber = ((Node) numberNm.item(0))
.getNodeValue().substring(2);
NodeList txtNmElmntLst = fstElmnt
.getElementsByTagName("text");
Element txtNmElmnt = (Element) txtNmElmntLst.item(0);
NodeList txtNm = txtNmElmnt.getChildNodes();
String text = ((Node) txtNm.item(0)).getNodeValue();
NodeList rcvNmElmntLst = fstElmnt
.getElementsByTagName("received");
Element rcvNmElmnt = (Element) rcvNmElmntLst.item(0);
NodeList rcvNm = rcvNmElmnt.getChildNodes();
String recievedDate = ((Node) rcvNm.item(0)).getNodeValue();
}
}
Can anyone guide me how this is done?
Thanks in advance.
Node.getAttributes()
NamedNodeMap attributes = fstElmnt.getAttributes();
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
You could avoid traversing if you use XPATH to retrieve the data. Read this tutorial.
I have been playing with Apache Xerces for parsing DOM. But it was horrible tasks. If you could, take a look at jsoup.
So, if your question has an answer in Jsoup, it would be:
node.attr("status")
I'm using DOM to parse xml, but have run into an issue. In my xml i have three tags namely str, int and str. Now while parsing i get the same value for both the str tags whereas they should be different.
My XML
<result name="response" numFound="62996" start="0">
<doc>
<str name="body">
a b c d e f g h i j k l m n o p q r s t u v w x y z
</str>
<int name="content_id">123351</int>
<str name="title">
Alphabets
</str>
</doc>
</result>
Code for xml parsing
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(gXml));
Document doc = db.parse(is);
NodeList infraline1 = doc.getElementsByTagName(node);
sb.append("<results count=");
sb.append("\"10\"");
sb.append(">\r\n");
for (int i = 0; i < infraline1.getLength(); i++) {
Node node1 = infraline1.item(i);
if (node1.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node1;
NodeList nodelist = element.getElementsByTagName("str");
Element element1 = (Element) nodelist.item(0);
NodeList body = element1.getChildNodes();
sb.append("<result>\r\n");
sb.append("<body>");
sb.append((body.item(0)).getNodeValue().trim());
sb.append("</body>\r\n");
if (node1.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node1;
NodeList nodelist1 = element2.getElementsByTagName("int");
Element element3 = (Element) nodelist1.item(0);
NodeList id = element3.getChildNodes();
sb.append("<id>");
sb.append(id.item(0).getNodeValue().trim());
sb.append("</id>\r\n");
}
if(node1.getNodeType() == Node.ELEMENT_NODE){
Element element4 = (Element) node1;
NodeList nodelist2 = element4.getElementsByTagName("str");
Element element5 = (Element) nodelist2.item(0);
NodeList title = element5.getChildNodes();
sb.append("<title>");
sb.append(title.item(0)).getNodeValue());
sb.append("</title>\r\n");
}
sb.append("</result>\r\n");
}
}
sb.append("</results>");
}
Please help as i need to get different values for both str node
I only see the statements
Element element1 = (Element) nodelist.item(0);
and
Element element3 = (Element) nodelist.item(0);
Are you sure, you are accesing the right elements.
... and by the way. The code is really confused, because you are parsing and writing data at once. Try to put the parsed XML into an own Object or Map and than write (format) it