Reputation: 569
I have this response string as XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:SRVResponse>
<ns:Response>
<ns1:ServiceHeader>
<ns1:rsHeader>
<ns1:status>
<ns1:finStatus>E</ns1:finStatus>
</ns1:status>
</ns1:rsHeader>
</ns1:ServiceHeader>
</ns:Response>
</ns:SRVResponse>
</soapenv:Body>
</soapenv:Envelope>
Im trying to fetch this finStatus tag value. This comes as part of ns1, and some times it comes as ns2. So, I dont want to depend on this. I just need to fetch if the tag has finStatus tag.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(strResponse));
if(is != null) {
Document doc = db.parse(is);
NodeList idDetails = doc.getDocumentElement().getElementsByTagNameNS("*", "status");
if(idDetails != null) {
int length = idDetails.getLength();
for (int i = 0; i < length; i++) {
if (idDetails.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) idDetails.item(i);
if (el.getNodeName().contains("status")) {
status = getElementTextContent(el, "ns1:finStatus");
System.out
.println("Status :"+status);
}
}
}
}
}
public static String getElementTextContent(Element el, String elemTag) {
String result = "";
if(el.getElementsByTagName(elemTag) != null) {
if(el.getElementsByTagName(elemTag).item(0) != null) {
if(el.getElementsByTagName(elemTag).item(0).getTextContent() != null) {
result = el.getElementsByTagName(elemTag).item(0).getTextContent();
} else {
result = "";
}
}
}
return result;
}
This is working only because Im passing the tag as ns1:finStatus,
How can I achieve this , not to based on namespace tag.
Upvotes: 0
Views: 191
Reputation: 163262
Install an XPath 2.0 library and do //*:finStatus
. Doing this by DOM navigation is just masochism. Either that, or you're being paid for the number of lines of code you write.
Upvotes: 1
Reputation: 4507
1) You are already fetching node without namespace using. So I do not see problem.
2) Use the * search in your second method as well i.e in your getElementTextContent(), use el.getElementsByTagNameNS("*",elemTag)
.
3) To skip the ns: prefix before passing it to getElementTextContent, Use getLocalName()
instead of getNodeName()
Upvotes: 1