0

I have the following XML:

<yweather:condition text="Fair" code="34" temp="21">

and Java code:

NodeList titleList = e.getElementsByTagName("yweather");
Element titleElem = (Element) titleList.item(0);
Node titleNode = titleElem.getChildNodes().item(0);

I am able to read other nodes but not the one with attributes. How do I get out the "temp" attribute?

KaiteN
  • 53
  • 7
  • looks like a duplicate of [Getting an attribute value in xml element](http://stackoverflow.com/questions/4138754/getting-an-attribute-value-in-xml-element) – Sanj Apr 13 '15 at 17:12

2 Answers2

2

The node for weather is called "condition" not "yweather", yweather is the namespace prefix.

so:

NodeList titleList = e.getElementsByTagName("condition");

if it does not help, you have two options, get all the elements with "*" and filter the one which tagName equals "condition"), or you need to check what is the namespace for the prefix "yweather" (somewhere at the top fo the xml document), and use it. For example if

xmlns:yweather="http://www.yahoo"

then use:

NodeList titleList = e.getElementsByTagNameNS("http://www.yahoo","condition");
Zielu
  • 8,312
  • 4
  • 28
  • 41
  • you need to give the whole namespace, somwhere on top of your xml is xmlns:yweather="xxxx" you need to provide those "xxxx" – Zielu Apr 13 '15 at 17:24
  • NodeList titleList = e.getElementsByTagNameNS("nameSpaceUrl", "condition"); print returns 0 – KaiteN Apr 13 '15 at 17:37
  • if your "e" element the parent of yweather:condition? call e.getElementsByTagName("*") and print all the results, you will see where you are and what are the children. – Zielu Apr 13 '15 at 17:42
  • NodeList titleList = e.getElementsByTagName("*"); Node temperature = titleList.item(5).getAttributes().item(2); String result = temperature.getTextContent(); System.out.println(result); Was the only way I got it to work, thank you for the help. – KaiteN Apr 13 '15 at 17:54
  • don't hard code element position (5) or attribute(2), if get tag by names does not work at least iterate over all returned elements and compare their names with "condition", same with temp attribute. Otherwise you will get bug if not elements are present or attributes order changes. – Zielu Apr 13 '15 at 18:06
0

You could:

File file = new File(//yourXMLfilenameHere//);
String xmlString = StringUtils.readFileToString(file);

String[] xmlTags = StringUtils.substringsBetween(xmlString,"<", ">");
int tagCount = xmlTags.length();
String[][] thisTag = new String[tagCount][4]; 

for (int ndx = 0; ndx < tagCount; ndx++) 
    thisTag[ndx][] = xmlTags[ndx].split(" ");

Then according to your format, thisTag[ndx][4].equals("temp=\"21\"");

that-ru551an-guy
  • 300
  • 1
  • 12