Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to find nodes in XML using ChildNodes.FindNode

Tags:

xml

delphi

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?

like image 986
user2168821 Avatar asked Mar 14 '13 08:03

user2168821


1 Answers

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', '');
like image 141
whosrdaddy Avatar answered Sep 17 '22 17:09

whosrdaddy