Leitura de arquivo XML

2 respostas
C

Tenho a seguinte classe para ler um xml:

import <a href="http://java.io">java.io</a>.<em>;

import <a href="http://java.net">java.net</a>.</em>;

import java.util.<em>;

import javax.xml.parsers.</em>;

import org.w3c.dom.*;

public class XmlReader {

// Caminho (path) do arquivo XML
private String xmlPathname;

// Construtor que seta o caminho do XML

public XmlReader( String path ) {

xmlPathname = path;

}

public Vector lerViolacao() throws Exception {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( xmlPathname );

Element file = doc.getDocumentElement();
Element violation = doc.getDocumentElement();

NodeList nl = file.getElementsByTagName( "file" );
NodeList n2 = violation.getElementsByTagName( "violation" );

Vector violacoes = new Vector();
Vector descricoes = new Vector();

for( int i=0; i<nl.getLength() && i<n2.getLength(); i++ ) {
  
  Element tagFile = (Element) nl.item( i );
  
  Element tagViolation = (Element) n2.item( i );
  
  
  
  String nomeArq = tagFile.getAttribute( "name");
  
  
  String descricao = getChildTagValue( tagFile, "violation" );
  String linha = tagViolation.getAttribute( "line");
  		
  Violacao violacao = new Violacao( nomeArq, descricao, linha );
  // Armazena uma violacao ( nomeArq, descricao, linha ) em uma posicao do vetor violacoes
  violacoes.addElement( violacao );  

}

return violacoes;

}

private String getChildTagValue( Element elem, String tagName ) throws Exception {

NodeList children = elem.getElementsByTagName( tagName );
if( children == null ) return null;
Element child = (Element) children.item(0);
if( child == null ) return null;
return child.getFirstChild().getNodeValue();

}
}

funcionaria se a estrutura do xml fosse assim:



mas tenho uma estrutura assim:

Como faço para ler todas as tags violation dentro da tag file, e não só a primeira?

2 Respostas

B

Caro Cass,

Trabalho com arquivo XML e utilizo um listIterator da seguinte forma:

protected ListIterator itemList = null;
itemList = root.getChild("item").listIterator();
while (itemList.hasNext()) {
Element item = (Element)itemList.next();
// Aqui eu trabalho as informações decada <tag>
}

Tenta fazer algo semelhante. se não funcionar, me avisa!

[],

Tkm

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

troca o seu for por este e ver o que acontece.

Criado 7 de junho de 2006
Ultima resposta 7 de jun. de 2006
Respostas 2
Participantes 3