Alguém tem solução para este erro?
Exception in thread “AWT-EventQueue-0” java.lang.AbstractMethodError: Receiver class org.apache.xerces.dom.DeferredElementImpl does not define or inherit an implementation of the resolved method ‘abstract java.lang.String getTextContent()’ of interface org.w3c.dom.Node.
at View.LerXmlView.lerXML(LerXmlView.java:191)
at View.LerXmlView.btnLeituraActionPerformed(LerXmlView.java:120)
at View.LerXmlView$1.actionPerformed(LerXmlView.java:59)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2314)
at java.desktop/javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:407)
at java.desktop/javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262)
at java.desktop/javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279)
at java.desktop/java.awt.Component.processMouseEvent(Component.java:6620)
at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3398)
at java.desktop/java.awt.Component.processEvent(Component.java:6385)
at java.desktop/java.awt.Container.processEvent(Container.java:2266)
at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4995)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4827)
at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4575)
at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4827)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:775)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:720)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:714)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:98)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:747)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:400)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:744)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
O que tem nessa linha?
Tem certeza de que não está chamando o getTextContent()
em um elemento inválido?
bom dia, ele esta dando erro no getTextContent() já fiz varias pesquisas e nao consegui a devida solucão
dá este erro java.lang.AbstractMethodError: Receiver class org.apache.xerces.dom.DeferredElementImpl does not define or inherit an implementation of the resolved method ‘abstract java.lang.String getTextContent()’ of interface org.w3c.dom.Node.
Sim, você já postou o StackTrace acima.
O que tem nesse código View.LerXmlView.lerXML(LerXmlView.java:191)
?
Teria como postar também o XML que está lendo?
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<codigo_autenticidade>0174270042260340</codigo_autenticidade>
<numero_nfse>23</numero_nfse>
<serie_nfse>1</serie_nfse>
<data_fato_gerador>04/01/2022</data_fato_gerador>
<data_nfse>04/01/2022</data_nfse>
<hora_nfse>08:33:05</hora_nfse>
<valor_total>540,00</valor_total>
<valor_desconto>0,00</valor_desconto>
<valor_ir>0,00</valor_ir>
<valor_inss>0,00</valor_inss>
<valor_contribuicao_social>0,00</valor_contribuicao_social>
<valor_rps>0,00</valor_rps>
<valor_pis>0,00</valor_pis>
<valor_cofins>0,00</valor_cofins>
39227132000196
7427
J
6276902000565
<nome_razao_social>SMP - INDUSTRIA E COMERCIO DE MOVEIS LTDA</nome_razao_social>
<sobrenome_nome_fantasia>SMP - INDUSTRIA E COMERCIO LTDA</sobrenome_nome_fantasia>
RUA JURUTAU, 1731
CONTABILIDADE@ACF.COM.BR
<ponto_referencia/>
PQ. INDUSTRIAL II
ARAPONGAS
86703070
<ddd_fone_comercial>43</ddd_fone_comercial>
<fone_comercial>43</fone_comercial>
<ddd_fone_residencial/>
<fone_residencial/>
<ddd_fax/>
<fone_fax/>
<codigo_local_prestacao_servico>7427</codigo_local_prestacao_servico>
<codigo_item_lista_servico>1401</codigo_item_lista_servico>
PRESTAÇÃO DE SERVIÇOS 6 HORAS TECINICAS
<aliquota_item_lista_servico>2,0000</aliquota_item_lista_servico>
<situacao_tributaria>0</situacao_tributaria>
<valor_tributavel>540,00</valor_tributavel>
<valor_deducao>0,00</valor_deducao>
<valor_issrf>0,00</valor_issrf>
<tributa_municipio_prestador>S</tributa_municipio_prestador>
<unidade_codigo/>
<unidade_quantidade/>
<unidade_valor_unitario/>
o conteúdo do campo do XML não consigo pois da erro no getTextContent()
Aparentemente esse XML não está correto, tem um monte de texto solto que não está dentro de nenhuma tag.
-
-
<codigo_autenticidade>0174270042260340</codigo_autenticidade>
<numero_nfse>23</numero_nfse>
<serie_nfse>1</serie_nfse>
<data_fato_gerador>04/01/2022</data_fato_gerador>
<data_nfse>04/01/2022</data_nfse>
<hora_nfse>08:33:05</hora_nfse>
<valor_total>540,00</valor_total>
<valor_desconto>0,00</valor_desconto>
<valor_ir>0,00</valor_ir>
<valor_inss>0,00</valor_inss>
<valor_contribuicao_social>0,00</valor_contribuicao_social>
<valor_rps>0,00</valor_rps>
<valor_pis>0,00</valor_pis>
<valor_cofins>0,00</valor_cofins>
-
39227132000196
7427
-
J
6276902000565
<nome_razao_social>SMP - INDUSTRIA E COMERCIO DE MOVEIS LTDA</nome_razao_social>
<sobrenome_nome_fantasia>SMP - INDUSTRIA E COMERCIO LTDA</sobrenome_nome_fantasia>
RUA JURUTAU, 1731
CONTABILIDADE@ACF.COM.BR
<ponto_referencia/>
PQ. INDUSTRIAL II
ARAPONGAS
86703070
<ddd_fone_comercial>43</ddd_fone_comercial>
<fone_comercial>43</fone_comercial>
<ddd_fone_residencial/>
<fone_residencial/>
<ddd_fax/>
<fone_fax/>
-
-
<codigo_local_prestacao_servico>7427</codigo_local_prestacao_servico>
<codigo_item_lista_servico>1401</codigo_item_lista_servico>
PRESTAÇÃO DE SERVIÇOS 6 HORAS TECINICAS
<aliquota_item_lista_servico>2,0000</aliquota_item_lista_servico>
<situacao_tributaria>0</situacao_tributaria>
<valor_tributavel>540,00</valor_tributavel>
<valor_deducao>0,00</valor_deducao>
<valor_issrf>0,00</valor_issrf>
<tributa_municipio_prestador>S</tributa_municipio_prestador>
<unidade_codigo/>
<unidade_quantidade/>
<unidade_valor_unitario/>
Quando postar código, utiliza o botão de texto pré-formatado do fórum, senão fica ruim de ler.
Seu XML continua mal formado
<?xml version="1.0" encoding="ISO-8859-1"?>
-
-
<codigo_autenticidade>0174270042260340</codigo_autenticidade>
<numero_nfse>23</numero_nfse>
<serie_nfse>1</serie_nfse>
<data_fato_gerador>04/01/2022</data_fato_gerador>
<data_nfse>04/01/2022</data_nfse>
<hora_nfse>08:33:05</hora_nfse>
<valor_total>540,00</valor_total>
<valor_desconto>0,00</valor_desconto>
<valor_ir>0,00</valor_ir>
<valor_inss>0,00</valor_inss>
<valor_contribuicao_social>0,00</valor_contribuicao_social>
<valor_rps>0,00</valor_rps>
<valor_pis>0,00</valor_pis>
<valor_cofins>0,00</valor_cofins>
-
39227132000196
7427
-
J
6276902000565
<nome_razao_social>SMP - INDUSTRIA E COMERCIO DE MOVEIS LTDA</nome_razao_social>
<sobrenome_nome_fantasia>SMP - INDUSTRIA E COMERCIO LTDA</sobrenome_nome_fantasia>
RUA JURUTAU, 1731
CONTABILIDADE@ACF.COM.BR
<ponto_referencia/>
PQ. INDUSTRIAL II
ARAPONGAS
86703070
<ddd_fone_comercial>43</ddd_fone_comercial>
<fone_comercial>43</fone_comercial>
<ddd_fone_residencial/>
<fone_residencial/>
<ddd_fax/>
<fone_fax/>
-
-
<codigo_local_prestacao_servico>7427</codigo_local_prestacao_servico>
<codigo_item_lista_servico>1401</codigo_item_lista_servico>
PRESTAÇÃO DE SERVIÇOS 6 HORAS TECINICAS
<aliquota_item_lista_servico>2,0000</aliquota_item_lista_servico>
<situacao_tributaria>0</situacao_tributaria>
<valor_tributavel>540,00</valor_tributavel>
<valor_deducao>0,00</valor_deducao>
<valor_issrf>0,00</valor_issrf>
<tributa_municipio_prestador>S</tributa_municipio_prestador>
<unidade_codigo/>
<unidade_quantidade/>
<unidade_valor_unitario/>
Antes das seguintes tags tem um monte de texto solto no arquivo:
codigo_autenticidade
nome_razao_social
ponto_referencia
aliquota_item_lista_servico
codigo_local_prestacao_servico
ddd_fone_comercial
codigo_local_prestacao_servico
Você não tem nenhum XSD para verificar se seu XML está sendo gerado corretamente?
Esse XML parece OK.
Provavelmente o erro está no seu código Java, deve estar tentando recuperar texto de uma TAG que não comporta texto.
O que tem nessa linha View.LerXmlView.lerXML(LerXmlView.java:191)
?
obrigado por tentar me ajudar, vou continuar pesquisando aqui até achar. vlw
Talvez se partilhares o teu código alguem te consiga ajudar. Assim, só com o stacktrace é praticamente impossivel.
/*
- Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
- Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package View;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
//import org.w3c.dom.Document;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.FilenameFilter;
/**
*
-
@author “Adilson Benedito da Silva”
*/
public class LerXmlView extends javax.swing.JFrame {/**
- Creates new form LerXmlView
*/
private final String DirectoryXML;
private ArrayList AL_FileName = new ArrayList();
private Integer iCount;
public LerXmlView() {
initComponents();
this.setType(java.awt.Window.Type.UTILITY);
setTitle(“Ler arquivo XML”);
DirectoryXML = MenuPrincipalView.vs_Diretory;
}/**
-
This method is called from within the constructor to initialize the form.
-
WARNING: Do NOT modify this code. The content of this method is always
-
regenerated by the Form Editor.
*/
@SuppressWarnings(“unchecked”)
//
private void initComponents() {btnLeitura = new javax.swing.JButton();
btnLoadXML = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
lstFileName = new javax.swing.JList<>();
lblRegistros = new java.awt.Label();setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
btnLeitura.setFont(new java.awt.Font(“Arial”, 1, 10)); // NOI18N
btnLeitura.setText(“Ler XML”);
btnLeitura.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLeituraActionPerformed(evt);
}
});btnLoadXML.setFont(new java.awt.Font(“Arial”, 1, 10)); // NOI18N
btnLoadXML.setForeground(new java.awt.Color(0, 153, 0));
btnLoadXML.setText(“Load XML”);
btnLoadXML.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadXMLActionPerformed(evt);
}
});jScrollPane1.setViewportView(lstFileName);
lblRegistros.setFont(new java.awt.Font(“Arial”, 1, 10)); // NOI18N
lblRegistros.setForeground(new java.awt.Color(0, 0, 255));javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(lblRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(btnLoadXML)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnLeitura, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLeitura)
.addComponent(btnLoadXML))
.addComponent(lblRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(49, Short.MAX_VALUE))
);lblRegistros.getAccessibleContext().setAccessibleName(“”);
setSize(new java.awt.Dimension(416, 318));
setLocationRelativeTo(null);
}//
private void btnLeituraActionPerformed(java.awt.event.ActionEvent evt) {
iCount = 0;
Iterator iterator = AL_FileName.iterator();
while (iterator.hasNext()) {
try {
// System.out.printf(“Posição %d- %s\n”, iCount, iterator.next());
lerXML(iterator.next());
} catch (Exception ex) {
Logger.getLogger(LerXmlView.class.getName()).log(Level.SEVERE, null, ex);
}
iCount++;
}
// try {
// lerXML(“”);
// } catch (Exception ex) {
// JOptionPane.showMessageDialog(null, "Erro ao ler arquivo XML " + ex);
// }
}private void btnLoadXMLActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel model = new DefaultListModel();
String vs_TipoArquivo = “/XML”;
String vs_PathFile = DirectoryXML + vs_TipoArquivo;
String vs_FileName;
File file = new File(vs_PathFile);
File LF[] = file.listFiles();
iCount = 0;
AL_FileName.clear();
model.clear();
for (int j = LF.length; iCount < j; iCount++) {
if (LF[iCount].getName().endsWith(“xml”)) {
File arquivos = LF[iCount];
// System.out.println(arquivos.getName());
vs_FileName = vs_PathFile + “/” + arquivos.getName();
AL_FileName.add(vs_FileName);
// model.addElement(arquivos.getName());
model.addElement(arquivos.getName());
lstFileName.setModel(model);
// try {
// lerXML(vs_FileName);
// } catch (Exception ex) {
// Logger.getLogger(LerXmlView.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
lblRegistros.setText(“Total de NFSe.: <” + iCount + “>”);
}private static void lerXML(String NomeArquivo) throws Exception {
// File fXmlFile = new File(“Agenda.xml”);
try {
File xmlDoc = new File(NomeArquivo);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlDoc);//System.out.println("Root do elemento: " + doc.getDocumentElement().getNodeName()); NodeList NL = doc.getElementsByTagName("nf"); int tmhLst = NL.getLength(); for (int i = 0; i < tmhLst; i++) { Node ndXML = NL.item(i); if (ndXML.getNodeType() == Node.ELEMENT_NODE) { Element elm = (Element) ndXML; NodeList elmFilho = elm.getChildNodes(); int tmhLstFilho = elmFilho.getLength(); for (int j = 0; j < tmhLstFilho; j++) { Node ndFilho = elmFilho.item(j); if (ndFilho.getNodeType() == Node.ELEMENT_NODE) { Element elmF = (Element) ndFilho;
- Creates new form LerXmlView
// System.out.println(elmF.getTagName());
if (elmF.getTagName().equals(“numero_nfse”)) {
String vlr = elmF.getTagName();
System.out.println("numero_nfse : " + elmF.getTextContent());
}
switch (elmF.getTagName()) {
case “cNF” → {
System.out.println("elmF.getNodeValue… : " + elmF.getNodeValue());
System.out.println("elmF.getPrefix …: " + elmF.getPrefix());
System.out.println("elmF.getTagName …: " + elmF.getTagName());
System.out.println("elmF.getTextContent .: " + elmF.getTextContent());
}
case “numero_nfse” → {
System.out.println("numero_nfse : " + elmF.getTextContent());
}
case “serie_nfse” → {
System.out.println("serie_nfse : " + elmF.getTextContent());
}
case “data_fato_gerador” → {
System.out.println("data_fato_gerador : " + elmF.getTextContent());
}
case “data_nfse” → {
System.out.println("data_nfse : " + elmF.getTextContent());
}
case “hora_nfse” → {
System.out.println("hora_nfse : " + elmF.getTextContent());
}
case “valor_total” → {
System.out.println("valor total : " + elmF.getTextContent());
}
case “valor_desconto” → {
System.out.println("valor_desconto : " + elmF.getTextContent());
}
case “valor_ir” → {
System.out.println("valor_ir : " + elmF.getTextContent());
}
case “valor_inss” → {
System.out.println("valor_inss : " + elmF.getTextContent());
}
case “valor_contribuicao_social” → {
System.out.println("valor_contribuicao_social : " + elmF.getTextContent());
}
case “valor_rps” → {
System.out.println("valor_rps : " + elmF.getTextContent());
}
case “valor_pis” → {
System.out.println("valor_pis : " + elmF.getTextContent());
}
case “valor_cofins” → {
System.out.println("valor_cofins : " + elmF.getTextContent());
}
}
}
}
}
}
} catch (IOException | ParserConfigurationException | DOMException | SAXException e) {
}
}
public void CarregarArquivoXML() {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new LerXmlView().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnLeitura;
private javax.swing.JButton btnLoadXML;
private javax.swing.JScrollPane jScrollPane1;
private java.awt.Label lblRegistros;
private javax.swing.JList<String> lstFileName;
// End of variables declaration
}
System.out.println("numero_nfse : " + elmF.getTextContent());
neste getTextContent() que esta dando o erro
/*
- Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
- Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package View;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
//import org.w3c.dom.Document;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.FilenameFilter;
/**
*
-
@author “Adilson Benedito da Silva”
*/
public class LerXmlView extends javax.swing.JFrame {/**
- Creates new form LerXmlView
*/
private final String DirectoryXML;
private ArrayList AL_FileName = new ArrayList();
private Integer iCount;
public LerXmlView() {
initComponents();
this.setType(java.awt.Window.Type.UTILITY);
setTitle(“Ler arquivo XML”);
DirectoryXML = MenuPrincipalView.vs_Diretory;
}/**
-
This method is called from within the constructor to initialize the form.
-
WARNING: Do NOT modify this code. The content of this method is always
-
regenerated by the Form Editor.
*/
@SuppressWarnings(“unchecked”)
//
private void initComponents() {btnLeitura = new javax.swing.JButton();
btnLoadXML = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
lstFileName = new javax.swing.JList<>();
lblRegistros = new java.awt.Label();setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
btnLeitura.setFont(new java.awt.Font(“Arial”, 1, 10)); // NOI18N
btnLeitura.setText(“Ler XML”);
btnLeitura.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLeituraActionPerformed(evt);
}
});btnLoadXML.setFont(new java.awt.Font(“Arial”, 1, 10)); // NOI18N
btnLoadXML.setForeground(new java.awt.Color(0, 153, 0));
btnLoadXML.setText(“Load XML”);
btnLoadXML.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadXMLActionPerformed(evt);
}
});jScrollPane1.setViewportView(lstFileName);
lblRegistros.setFont(new java.awt.Font(“Arial”, 1, 10)); // NOI18N
lblRegistros.setForeground(new java.awt.Color(0, 0, 255));javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(lblRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(btnLoadXML)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnLeitura, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLeitura)
.addComponent(btnLoadXML))
.addComponent(lblRegistros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(49, Short.MAX_VALUE))
);lblRegistros.getAccessibleContext().setAccessibleName(“”);
setSize(new java.awt.Dimension(416, 318));
setLocationRelativeTo(null);
}//
private void btnLeituraActionPerformed(java.awt.event.ActionEvent evt) {
iCount = 0;
Iterator iterator = AL_FileName.iterator();
while (iterator.hasNext()) {
try {
// System.out.printf(“Posição %d- %s\n”, iCount, iterator.next());
lerXML(iterator.next());
} catch (Exception ex) {
Logger.getLogger(LerXmlView.class.getName()).log(Level.SEVERE, null, ex);
}
iCount++;
}
// try {
// lerXML(“”);
// } catch (Exception ex) {
// JOptionPane.showMessageDialog(null, "Erro ao ler arquivo XML " + ex);
// }
}private void btnLoadXMLActionPerformed(java.awt.event.ActionEvent evt) {
DefaultListModel model = new DefaultListModel();
String vs_TipoArquivo = “/XML”;
String vs_PathFile = DirectoryXML + vs_TipoArquivo;
String vs_FileName;
File file = new File(vs_PathFile);
File LF[] = file.listFiles();
iCount = 0;
AL_FileName.clear();
model.clear();
for (int j = LF.length; iCount < j; iCount++) {
if (LF[iCount].getName().endsWith(“xml”)) {
File arquivos = LF[iCount];
// System.out.println(arquivos.getName());
vs_FileName = vs_PathFile + “/” + arquivos.getName();
AL_FileName.add(vs_FileName);
// model.addElement(arquivos.getName());
model.addElement(arquivos.getName());
lstFileName.setModel(model);
// try {
// lerXML(vs_FileName);
// } catch (Exception ex) {
// Logger.getLogger(LerXmlView.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
lblRegistros.setText(“Total de NFSe.: <” + iCount + “>”);
}private static void lerXML(String NomeArquivo) throws Exception {
// File fXmlFile = new File(“Agenda.xml”);
try {
File xmlDoc = new File(NomeArquivo);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlDoc);//System.out.println("Root do elemento: " + doc.getDocumentElement().getNodeName()); NodeList NL = doc.getElementsByTagName("nf"); int tmhLst = NL.getLength(); for (int i = 0; i < tmhLst; i++) { Node ndXML = NL.item(i); if (ndXML.getNodeType() == Node.ELEMENT_NODE) { Element elm = (Element) ndXML; NodeList elmFilho = elm.getChildNodes(); int tmhLstFilho = elmFilho.getLength(); for (int j = 0; j < tmhLstFilho; j++) { Node ndFilho = elmFilho.item(j); if (ndFilho.getNodeType() == Node.ELEMENT_NODE) { Element elmF = (Element) ndFilho;
- Creates new form LerXmlView
// System.out.println(elmF.getTagName());
if (elmF.getTagName().equals(“numero_nfse”)) {
String vlr = elmF.getTagName();
System.out.println("numero_nfse : " + elmF.getTextContent());
}
switch (elmF.getTagName()) {
case “cNF” → {
System.out.println("elmF.getNodeValue… : " + elmF.getNodeValue());
System.out.println("elmF.getPrefix …: " + elmF.getPrefix());
System.out.println("elmF.getTagName …: " + elmF.getTagName());
System.out.println("elmF.getTextContent .: " + elmF.getTextContent());
}
case “numero_nfse” → {
System.out.println("numero_nfse : " + elmF.getTextContent());
}
case “serie_nfse” → {
System.out.println("serie_nfse : " + elmF.getTextContent());
}
case “data_fato_gerador” → {
System.out.println("data_fato_gerador : " + elmF.getTextContent());
}
case “data_nfse” → {
System.out.println("data_nfse : " + elmF.getTextContent());
}
case “hora_nfse” → {
System.out.println("hora_nfse : " + elmF.getTextContent());
}
case “valor_total” → {
System.out.println("valor total : " + elmF.getTextContent());
}
case “valor_desconto” → {
System.out.println("valor_desconto : " + elmF.getTextContent());
}
case “valor_ir” → {
System.out.println("valor_ir : " + elmF.getTextContent());
}
case “valor_inss” → {
System.out.println("valor_inss : " + elmF.getTextContent());
}
case “valor_contribuicao_social” → {
System.out.println("valor_contribuicao_social : " + elmF.getTextContent());
}
case “valor_rps” → {
System.out.println("valor_rps : " + elmF.getTextContent());
}
case “valor_pis” → {
System.out.println("valor_pis : " + elmF.getTextContent());
}
case “valor_cofins” → {
System.out.println("valor_cofins : " + elmF.getTextContent());
}
}
}
}
}
}
} catch (IOException | ParserConfigurationException | DOMException | SAXException e) {
}
}
public void CarregarArquivoXML() {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LerXmlView.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new LerXmlView().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnLeitura;
private javax.swing.JButton btnLoadXML;
private javax.swing.JScrollPane jScrollPane1;
private java.awt.Label lblRegistros;
private javax.swing.JList<String> lstFileName;
// End of variables declaration
}
lembrando que ele dá erro no getTextContent()
Edita suas postagens e formata o código Java com a opção de texto pré formatado do fórum.
Que versão de java estás a usar?
Esse código, embora pudesse ser bastante melhorado, executa e le o XML sem exceptions com java 8 e java 12