Getting XML node value

I know how to parse XML documents with the DOM when they are in the form:

<tagname> valueIWant </tagname> 

However, the element I'm trying to get is instead in the form

 <photo farm="9" id="8147664661" isfamily="0" isfriend="0" ispublic="1" owner=" 8437609@N04 " secret="4902a217af" server="8192" title="Rainbow"/> 

I usually use cel.getTextContent() to return a value, but in this case it does not work. And cel.getAttributes() , which I thought would work ...

Ideally, I just need to get the numerical values โ€‹โ€‹of id and owner. However, if someone can help with how to get all this, then I can handle removing parts that I don't need later.

+4
source share
2 answers

What you are looking for is the meaning of the various attributes that are attached to the element. Look at using the getAttribute(String name) method to achieve this

If you want to get all the attributes, all this can be done with getAttributes() and repeat it. An example of both of these methods might be something like this:

 private void getData(Document document){ if(document == null) return; NodeList list = document.getElementsByTagName("photo"); Element photoElement = null; if(list.getLength() > 0){ photoElement = (Element) list.item(0); } if(photoElement != null){ System.out.println("ID: "+photoElement.getAttribute("id")); System.out.println("Owner: "+photoElement.getAttribute("owner")); NamedNodeMap childList = photoElement.getAttributes(); Attr attribute; for(int index = 0; index < childList.getLength(); index++){ if(childList.item(index).getNodeType() == Node.ATTRIBUTE_NODE){ attribute = ((Attr)childList.item(index)); System.out.println(attribute.getNodeName()+" : "+attribute.getNodeValue()); }else{ System.out.println(childList.item(index).getNodeType()); } } } } 
+1
source

Sort of:

 Element photo = (Element)yournode; photo.getAttribute("farm"); 

will get the value of the farm attribute. You need to treat your node as an element in order to have access to these attributes ( doc ).

0
source

Source: https://habr.com/ru/post/1443678/


All Articles