Reputation: 1203
I'm trying to parse an XML document using DOM parser in java. I need to get the values of various attributes. I'm trying to parse the following document:
<?xml version="1.0" encoding="UTF-8"?>
<BirthResults>
<Results>
<Rejected>
<Reject>
<Birth Etg = "etg1"/>
<Causes>
<Cause Code = "test1" Desc = "Desc1"/>
</Causes>
</Reject>
<Reject>
<Birth Etg = "etg2"/>
<Causes>
<Cause Code = "test2" Desc = "Desc2"/>
</Causes>
</Reject>
</Rejected>
</Results>
</BirthResults>
Using the following code:
import java.io.InputStream;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.ksoap2.serialization.SoapObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Parsers {
String Etg, Dob, Breed, Brd, Sex, EId, GdEtg, SuEtg, SiEtg, BLoc, BSLoc,
PLoc, PSLoc, Code, Desc;
static String response;
public String Birth(InputStream in) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(in);
doc.getDocumentElement().normalize();
try {
NodeList list = doc.getElementsByTagName("Reject");
int L = list.getLength();
for (int x = 0; x < L; x++) {
setNull();
Node node = list.item(x);
NodeList sublist = node.getChildNodes();
for (int y = 0; y < sublist.getLength(); y++) {
Node finNode = (Node) sublist.item(y);
if (finNode.getNodeType() == Node.ELEMENT_NODE) {
Element fin = (Element) finNode;
getAttributes(fin);
}
}
}
}catch(Exception e){}
}catch(Exception e){}
}
private void getAttributes(Element fin) {
Etg = fin.getAttribute("Etg");
Code = fin.getAttribute("Code");
System.out.println(Etg + ":" + Code);
}
}
Whilst I get the value for Etg out, the values for Code and Desc are returned as blank. I'm assuming this is because they're embedded on a deeper 'tier' but I have no idea how to get around the problem.
Thanks a lot.
Upvotes: 3
Views: 6183
Reputation: 1806
NodeList sublist = node.getChildNodes();
assigns to sublist children, it means that there are assigned nodes: Birth, Causes
. The Causes
node contains list of children, so if your finNode
is Birth
element you can get Egt
attr, but if finNode
is Causes
you have to get children and then you can read Code
and Desc
from each children of 'Causes'.
For checking name of element you can use fin.getTagName()
Upvotes: 3