Reading values ​​from XML using child nodes with namespaces

I have 2 XML files, first this one that works fine:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns3:ConsultarSituacaoLoteRpsResposta xmlns:ns2="http://www.ginfes.com.br/tipos_v03.xsd" xmlns:ns3="http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_resposta_v03.xsd"> <ListaMensagemRetorno> <ns2:MensagemRetorno> <ns2:Codigo>E172</ns2:Codigo> </ns2:MensagemRetorno> </ListaMensagemRetorno> </ns3:ConsultarSituacaoLoteRpsResposta> 

The code I use to read it looks something like this:

 MyNode := Doc.DocumentElement.ChildNodes.First.ChildNodes.FindNode('MensagemRetorno'); MyValue := MyNode.ChildValues['Codigo']; 

The problem is that I have a second XML:

 <?xml version="1.0" encoding="utf-8"?> <ConsultarSituacaoLoteRpsResposta xmlns="http://www.issnetonline.com.br/webserviceabrasf/vsd/servico_consultar_situacao_lote_rps_resposta.xsd"> <ListaMensagemRetorno> <MensagemRetorno> <Codigo xmlns="http://www.issnetonline.com.br/webserviceabrasf/vsd/tipos_complexos.xsd">E156</Codigo> </MensagemRetorno> </ListaMensagemRetorno> </ConsultarSituacaoLoteRpsResposta> 

Note that this XML has a namespace in the "Codigo" node, so my code does not find this node.

The only way I found reading the value of "Codigo" from this second XML was as follows:

 for I := 0 to MyNode.ChildNodes.Count -1 do begin ChildNode := RetornoNode.ChildNodes[I]; if ChildNode.NodeName = 'Codigo' then Codigo := ChildNode.NodeValue; end; 

But I think that there should be a better way to do this, since I still have not understood why the first code does not work with the second XML.

Could someone clarify this for me?

+4
source share
1 answer

This seems to be a limitation of the ChildValues property ChildValues

You can use one of these alternatives to return a value

  MyNode := Doc.DocumentElement.ChildNodes.First.ChildNodes.FindNode('MensagemRetorno'); MyValue :=MyNode.ChildNodes.First.Text; 

or using an overloaded version of the FindNode method

  MyNode := Doc.DocumentElement.ChildNodes.First.ChildNodes.FindNode('MensagemRetorno'); MyValue:= MyNode.ChildNodes.FindNode('Codigo','http://www.issnetonline.com.br/webserviceabrasf/vsd/tipos_complexos.xsd').Text; 
+5
source

Source: https://habr.com/ru/post/1414151/


All Articles