Search code examples
xmldelphitxmldocument

Parse xml document - comment lines also identified as nodes


When processing an XML document, the 'comment' lines (starting with <!--) are also parsed as nodes. Example of xml:

<Message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <!-- Element comment -->
    <id extension="test"/>
</Message> 

Code to parse:

  XmlDoc := TXmlDocument.Create(nil);
  XmlDoc.LoadFromFile('C:\test.xml');

  msgNode := XMLDoc.ChildNodes.FindNode('Message');

  NofChildren := 0;
  for i := 0 to msgNode.ChildNodes.Count-1 do begin
    Inc(NofChildren);
    tmpNode := msgNode.ChildNodes[i];
    // for comment line: tmpNode.LocalName = ''
  end;

Previous code results in NofChildren = 2.

Is there a way to avoid the comment lines being treated/parsed as actual XML data?

Tested with RAD Studio 10.2.3 and 11.3.


Solution

  • My first solution consisted of checking the LocalName property.

    However I changed this to checking if NodeType <> ntComment.

    Note: this question was to ensure there wasn't any possibility to filter out the comments on parsing the XML document.