Read values from XML with ChildNodes with namespaces
delphi, delphi-xe2, dom, xml
Solution
This it seems a limitation of the `ChildValues` property
You can use one of these alternatives to return the value
MyNode := Doc.DocumentElement.ChildNodes.First.ChildNodes.FindNode('MensagemRetorno');
MyValue :=MyNode.ChildNodes.First.Text;
or using the 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;
Problem
I have 2 XML files, first this one which works just 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'm using to read it is 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> ``` Notice that this XML have a namespace in the "Codigo" node, so my code doesn't find this node. The only way I found to read the "Codigo" value from this second XML was like this: ``` 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, as I still didn't understand why the first code doesn't work with the second XML. Anyone could please clarify it for me?