Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test whether a certain XML node exists?

Tags:

xml

delphi

What is the proper way to test for the existance of an optional node? A snipped of my XML is:

<Antenna >
  <Mount Model="text" Manufacture="text">
   <BirdBathMount/>
  </Mount>
</Antenna>

But it could also be:

<Antenna >
  <Mount Model="text" Manufacture="text">
   <AzEl/>
  </Mount>
</Antenna>

The child of Antenna could either be BirdBath or AzEl but not both...

In Delphi XE I have tried:

 if (MountNode.ChildNodes.Nodes['AzEl'] <> unassigned then //Does not work
 if (MountNode.ChildNodes['BirdBathMount'].NodeValue <> null) then // Does not work
 if (MountNode.BirdBathMount.NodeValue <> null) then  // Does not work

I use XMLSpy to create the schema and the example XML and they parse correctly. I use Delphi XE to create the bindings and it works on most other combinations fine.

This must have a simple answer that I have just overlooked - but what? Thanks...... Jim

like image 957
Seti Net Avatar asked Jun 15 '12 22:06

Seti Net


1 Answers

You can use XPath, try this sample.

uses
  MSXML;


Var
  XMLDOMDocument  : IXMLDOMDocument;
  XMLDOMNode      : IXMLDOMNode;
begin
  XMLDOMDocument:=CoDOMDocument.Create;
  XMLDOMDocument.loadXML(XmlStr);
  XMLDOMNode := XMLDOMDocument.selectSingleNode('//Antenna/Mount/BirdBathMount');
  if XMLDOMNode<>nil then
    Writeln('BirdBathMount node Exist')
  else
  begin
    XMLDOMNode := XMLDOMDocument.selectSingleNode('//Antenna/Mount/AzEl');
    if XMLDOMNode<>nil then
      Writeln('AzEl node Exist');
  end;
end;
like image 187
RRUZ Avatar answered Oct 05 '22 23:10

RRUZ