Trying to find nodes in XML using ChildNodes.FindNode

16,611

The root node uses a namespace (AWS_SFC). Because of this, the childnodes in the XML document have to carry the same namespace, which is not the case in your XML document.

Just add a blank NameSpaceURI parameter to the FindNode procedure and it will find the node:

SFC_Type := SFC_Info.ChildNodes.FindNode('SFC_TYPE', '');
Share:
16,611
user2168821
Author by

user2168821

Updated on June 13, 2022

Comments

  • user2168821
    user2168821 almost 2 years

    I'm new to XML and am trying to use a Delphi XE TXMLDocument to access data in the following XML

    <?xml version="1.0" encoding="UTF-8" ?>
    <sfc:SFC xmlns:sfc="AWS_SFC">
        <ID>4294967295</ID>
        <SFC_TYPE>
            <WindSpeed>18</WindSpeed>
            <WindDir>123.6</WindDir>
            <Temperature>22.9</Temperature>
            <Pressure>1013.25</Pressure>
            <Humidity>57.9</Humidity>
            <DewPoint>16.8</DewPoint>
        </SFC_TYPE>'
        <Location>
            <longitude>18.5</longitude>
            <latitude>-34.5</latitude>
            <altitude>50.8</altitude>
        </Location>
        <StampDateTime>2012-12-17T09:30:47.0Z</StampDateTime>
    </sfc:SFC>
    

    My code starts off like this:

    var
      SFC_Info: IXMLNode;
      SFC_Type: IXMLNode;
    begin
      SFC_Info := XMLDocument1.DocumentElement;
      SFC_Type := SFC_Info.ChildNodes.First;
      while (SFC_Type.NodeName <> 'SFC_TYPE') do
        SFC_Type := SFC_TYPE.NextSibling;
      memDebug.Lines.Add('Wind speed = ' + SFC_Type.ChildNodes.FindNode('WindSpeed').Text);
      etc
    

    This does what I want, but using the loop seems messy. I would have thought that accessing the 'SFC_TYPE' node could be achieved with

      SFC_Type := SFC_Info.ChildNodes.FindNode('SFC_TYPE');
    

    but this returns nil.

    Am I missing something?

  • Jan Doggen
    Jan Doggen about 11 years
    @User2168821 The complexity of your namespaces is very limited. I had the same problem with XML containing several namespaces and decided to first strip them all, so that I do not continously run into this issue.
  • user2168821
    user2168821 about 11 years
    Thanks! The blank NameSpaceURI parameter made the difference.
  • whosrdaddy
    whosrdaddy about 11 years
    @JanDoggen: The problem only arises if the childnodes don't carry the namespace from the parentnode (which is incorrect by the way...)