Boa tarde!
Tenho um arquivo XML que é lido sem problemas pelo DOM, mas somente quando idento ele por algum editor de XML.
Alguns arquivos que eu processo, apesar de possuir a extensão xml, não possuem identação nenhuma. Eu os abros com um editor, idento-os e apartir dai o DOM acha as tags que eu preciso.
Alguem sabe por que isto ocorre?
try {
XmlChilds targets = new XmlChilds();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(isNfe);
// DOMConfiguration docConfig = doc.getDomConfig();
// docConfig.setParameter("well-formed", Boolean.TRUE);
// doc.normalizeDocument();
Element elem = doc.getDocumentElement();
NodeList n2 = elem.getElementsByTagName("obsCont");
System.out.println(targets.buscaFilhos(n2));
} catch (ParserConfigurationException e) {
System.out.println("Erro de ");
e.printStackTrace();
} catch (SAXException e) {
System.out.println("Segundo");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Terceiro");
e.printStackTrace();
}
package br.inf.gati.nfe.util;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XmlChilds {
public String buscaFilhos(NodeList nl) {
StringBuilder retorno_emails = new StringBuilder();
for (int i = 0; i <= nl.getLength(); i++) {
// Testa para ver se é um elemento
if (nl.item(i) instanceof Element) {
Element elem = null;
if (nl.item(i) == null) {
System.out.println("Não encontrado");
} else {
NodeList node = nl.item(i).getChildNodes();
//testa se tem filhos ou não se tiver chama o metodo novamente
if (node.getLength() > 1) {
elem = (Element) nl.item(i);
if (elem.getAttribute("xCampo").equalsIgnoreCase("E_MAIL")){
if (i == nl.getLength() - 1){
retorno_emails.append(elem.getTextContent().trim());
}else{
retorno_emails.append(elem.getTextContent().trim()).append(";");
}
}
} else {
buscaFilhos(node);
}
}
}else{
Node node = nl.item(i);
if (node == null){
}else{
//System.out.println("Else Name "+node.getNodeName());
//System.out.println("Else Valor "+node.getTextContent());
}
}
}
return retorno_emails.toString();
}
}