delphi – XML tags being generated with prefixes

Question:

I'm creating an XML file by Delphi and if I use the prefix in the creation of the first tag, the prefix "ns1" is added to all the tags that will come below, generating an error in the integration with the WebService. What I need is that the first tag is generated with the prefix and the others not.

When I use this command to create the first tag, the prefix is ​​repeated in all the others:

xDOC := TXMLDocument.Create(nil);
xDOC.Active := True;
xDOC.Encoding := 'UTF-8';

xNOD := xDOC.AddChild('ns1:ReqEnvioLoteRPS'); // Essa linha...
if not(xNOD.NodeName = 'ReqEnvioLoteRPS') then
  xNOD := xDOC.ChildNodes.FindNode('ReqEnvioLoteRPS');

xNOD := xNOD.AddChild('Cabecalho');

In this case, the tag "Cabaçalho" is generated like this: "ns1:Cabecalho" , giving an error in the integration, as it is requested that the header be like this: "Cabecalho" . If I generate the line without the prefix:

xNOD := xDOC.AddChild('ReqEnvioLoteRPS'); // Essa linha...

It gives an error, because the integration asks for this "ns1" in the first tag.

I need the "ns1" to be informed only in the main XML tag "ReqEnvioLoteRPS", and not in the others…

Answer:

When you use AddChild() to add a new child tag and you don't explicitly specify a namespace, the child tag inherits the parent tag's namespace.

This is behavior of AddChild() , you cannot change it. This is why the ns1: prefix is ​​inherited on all child nodes.

To solve this you can overload the AddChild() method.

See this answer , it is exactly the solution to your problem.

Scroll to Top
AllEscort