How to Parse Same Name Tag in Android Xml Dom Parsing

How to parse same name tag in xml using dom parser java?

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Element root = doc.getDocumentElement();
NodeList nodeList = doc.getElementsByTagName("player");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
// do your stuff
}

but I'd rather suggest to use XPath

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/GameWorld/player");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

Parsing XML with tags with same name on different levels in DOM

Try this ...

if(node.getNodeType() == Node.ELEMENT_NODE){
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("con");

if(!e.hasAttribute("idref")){
if(resultNodeList.getLength() == 2){
Element nameElement = (Element) resultNodeList.item(1);
if(!nameElement.hasAttribute("idref"))
System.out.println("Context ID Ref : "+null);
else
System.out.println("Context ID Ref :"+nameElement.getAttribute("idref"));
}else {
Element nameElement = (Element) resultNodeList.item(0);
if(!nameElement.hasAttribute("idref"))
System.out.println("Context ID Ref : "+null);
else
System.out.println("Context ID Ref :"+nameElement.getAttribute("idref"));
}
}
}

Parse Nested XML tags with the same name

If you are manual traversing the Xml, try using a variable which increments as you encounter each "e" tag, then decrements as you leave it.

If the source follows the above example you gave, you could use a simple if statement to make sure that the counter is equal to 2 before performing an action (assuming it started at 0)

I might have slightly misunderstood your exact problem, but I hope this helps.

Android xml parsing with same element name in android?

use this code may this will help..

   nodes1 = doc.getElementsByTagName("parent");                  

for (int i = 0; i < nodes1.getLength(); i++) {

ObjectClass cgro = new ObjectClass();
Element e = (Element)nodes1.item(i);
cgro.Title = XMLfunctions.getValue(e, "Title");

nodes1a = doc.getElementsByTagName("child");

for(int j = 0; j < nodes1a.getLength(); j++ ){

ObjectClass1 cgro1 = new ObjectClass1();

Element e2= (Element) nodes1a.item(j);
cgro1.child= XMLfunctions.getCharacterDataFromElement(e2);
ArrayListClass.ItemList1.add(cgro1);
}

ArrayListClass.ItemList2.add(cgro);

}

and class use for this

    public class XMLfunctions {

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;

}

/** Returns element value
* @param elem element (it is XML tag)
* @return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}

public static String getXML(){
String line = null;

try {

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://p-xr.com/xml");

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}

return line;

}

public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;

try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}

return res;
}

public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}

}

may this help you...

Is there a way to parse XML even though same Tag Names in diffrent Nodes

Element.getElementsByTagName("foo") returns all descendant elements (of the current element, with the given tag-/element name). In your code+sample this just throws a nasty NPE, because the first friends elements don't have a numberFriends inside.

Now you can:

  1. catch the NullPointerException (or otherwise test, whether you are in the correct element ...it's not my favorite approach, not clean, but quite pragmatic, short, and working).
  2. "drill down" into the xml structure, to pick the right things for you. (So, not obtain getElementsByTagName() ...from the (doc) root element, but from according sub-elements.) :

( for 2.) Assuming, you want names+ages of all //humans/human (<- XPATH) elements and the name+numberFriends from all //friend/friends elements, you'd do something like:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Test {

public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File("humanFriends.xml");
Document doc = builder.parse(file);

NodeList humansL = doc.getElementsByTagName("humans");
//System.out.println(humansL.getLength());
for (int i = 0; i < humansL.getLength(); i++) {
Node humansN = humansL.item(i);
if (humansN.getNodeType() == Node.ELEMENT_NODE) {
NodeList humanL = ((Element) humansN).getElementsByTagName("human");
// System.out.println(humanL.getLength());
for (int j = 0; j < humanL.getLength(); j++) {
Node humanN = humanL.item(j);
if (humanN.getNodeType() == Node.ELEMENT_NODE) {
Element humanE = (Element) humanN;
String name = humanE.getElementsByTagName("name").item(0).getTextContent();
String age= humanE.getElementsByTagName("age").item(0).getTextContent();
System.out.println(name);
System.out.println(age);
}
}
}
}

NodeList friendsL = doc.getElementsByTagName("friend");
// System.out.println(friendsL.getLength());
for (int i = 0; i < friendsL.getLength(); i++) {
Node friendsN = friendsL.item(i);
if (friendsN.getNodeType() == Node.ELEMENT_NODE) {
NodeList friendL = ((Element) friendsN).getElementsByTagName("friends");
// System.out.println(friendL.getLength());
for (int j = 0; j < friendL.getLength(); j++) {
Node friendN = friendL.item(j);
if (friendN.getNodeType() == Node.ELEMENT_NODE) {
Element friendE = (Element) friendN;
String name = friendE.getElementsByTagName("name").item(0).getTextContent();
System.out.println(name);
String numberFriends = friendE.getElementsByTagName("numberFriends").item(0).getTextContent();
System.out.println(numberFriends);
}
}
}
}
}
}

Please vary the values in your (test) "humanFriends.xml" somewhat, especially to recognize problems in ambiguous tag names;)

Java parse XML parent and child elements with the same name

You should use XPath to extract the right node like so:

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;

public class FindViaXpath {

private static final String XML =
" <server>\n" +
" <name>HTTP server</name>\n" +
" <ssl>\n" +
" <name>HTTPS server</name>\n" +
" <listen-port>8051</listen-port>\n" +
" </ssl>\n" +
" <listen-port>8050</listen-port>\n" +
" </server>";

public static void main(String[] args) {
System.out.println(XML);

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
StringReader reader = new StringReader(XML);
InputSource source = new InputSource(reader);
Document document = builder.parse(source);
XPath xpath = XPathFactory.newInstance().newXPath();
String port = (String) xpath.evaluate("//server/listen-port", document, XPathConstants.STRING);
System.out.println(String.format("Port: %s", port));
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
e.printStackTrace();
}
}
}


Related Topics



Leave a reply



Submit