Ler XML com DOM

3 respostas
JPinhead

Pessoal estou tentado ler um xml... fiz o código com base em um artigo aqui do guj mesmo, mas o meu xml é um pouco mais complexo... tenho tags "filhas" com os mesmos nomes em tags"pais" diferentes...

+ <principal>

+ <ide>
          <cUF>43</cUF> 
          <xNome>43</xNome> 
  </ide>

- <emit>
    <xNome>XXX S/A</xNome> 
  
   - <enderEmit>
           <xLgr>RUA MARIANTE</xLgr> 
           <nro>288</nro> 
      </enderEmit>
  
  </emit>

- <dest>
       <xNome>XXX LTDA</xNome> 

   - <enderDest>
          <xLgr>RUA GOMES CARDIM</xLgr> 
          <nro>235</nro> 
      </enderDest>

 </dest>

</principal>

Acho q vcs entenderam... por exemplo tenho a tag xNome filha de ide e filha de emit... tenho a tag xLgr filha de enderEmit e enderenderDest...
Como faço para capturar estas tags....

meu código pega como base a tag "principal" e busca os elementos, mas se tem o mesmo nome, não funciona...

meu código

...
{ 
   Element elem = doc.getDocumentElement();


   // pega todos os elementos do XML
    NodeList nl = elem.getElementsByTagName( "principal" );
 
    Vector vetPrinc = new Vector();
 
  for( int i=0; i<nl.getLength(); i++ ) {
  
  Element elemento = (Element) nl.item( i );
    
  principalBeans principalBeans = new principalBeans ();

       principalBeans .setIde_cUF(getChildTagValue( elemento , "cUF" ));
       principalBeans .setEmit_xNome(getChildTagValue( elemento , "xNome" ));

       // esta tag q repete
       principalBeans .setDest_xNome(getChildTagValue( elemento , "xNome" ));
      

      // adiciona na coleção 
      vetPrinc .addElement( principalBeans );
    }
     
   
         
      return vetPrinc ;
    }

 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();
  }
Acredito que tenho que informar uma tag pai neste processo, mas tentei adicionar outro elemento na função
getChildTagValue( tagpai, "xNome" ));
mas não funcionou :cry:

eaí pessoal como faço para resolver este problema?

3 Respostas

Guerr

Você já tentou utilizar o SAX? Acho que se você fizer um controle de pilha dentro do Handler o tratamento será bem mais tranquilo.

Diogo_Cabral

Oi,

Dá uma olhada no tutorial da XStream. Estou utilizando e estou gostando do resultado.

JPinhead

Amigos adicionei os elementos “filhos” que eu precisava ler, dentro da iteração principal… aparentemente está funcionando…

Está correto isso? Existe outra forma de fazer?
pergunto pq tenho quase 200 tags diferentes para ler no meu xml…

for( int i=0; i<nl.getLength(); i++ ) {
   
    Element elemento = (Element) nl.item( i );
   
//adicionei os elementos "filhos" como item "0" pq não haverá iteração neste caso
    NodeList nlEmit = taginfNfe.getElementsByTagName( "emit" );
    Element Emit = (Element) nlEmit.item( 0 );

    NodeList nlDest = taginfNfe.getElementsByTagName( "dest" );
    Element Dest = (Element) nlDest.item( 0 );

    principalBeans principalBeans = new principalBeans ();

    principalBeans .setIde_cUF(getChildTagValue( elemento , "cUF" ));

// chamei a tag do elento filho
    principalBeans .setEmit_xNome(getChildTagValue( Emit , "xNome" ));

    // esta tag q repete
    principalBeans .setDest_xNome(getChildTagValue( Dest , "xNome" ));


    // adiciona na coleção 
    vetPrinc .addElement( principalBeans );
     }

ps.: valeu pela sugestão do SAX e Xstream… mas no momento tenho que resolver isso com DOM…

Criado 29 de março de 2007
Ultima resposta 29 de mar. de 2007
Respostas 3
Participantes 3