How to check if any XML node exists?

What is the correct way to check for an optional node? I disabled my XML:

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

But it could also be:

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

The Antenna child can be either BirdBath or AzEl, but not both ...

In Delphi XE, I 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 XML schema and example, and they parse correctly. I use Delphi XE to create bindings and works great with most other combinations.

This should have a simple answer that I just forgot - but what? Thanks ... Jim

+6
source share
4 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; 
+8
source

Use .FindNode. It returns nil if node does not exist.

eg.

 xmlNode := MountNode.ChildNodes.FindNode('AzEl'); if Assigned(xmlNode) then ... 
+8
source

I have successfully tested it. with this code. This is somewhat more complicated and I need a root element.

Xmlfile

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

Delphi2010.pas

 procedure TForm1.RetrieveDocument; var LDocument: IXMLDocument; LNodeElement, LNode,BNode,CNode : IXMLNode; I: Integer; begin LDocument := TXMLDocument.Create(nil); LDocument.LoadFromFile(XmlFile); LNodeElement := LDocument.ChildNodes.FindNode('ThisIsTheDocumentElement'); if (LNodeElement <> nil) then begin for I := 0 to LNodeElement.ChildNodes.Count - 1 do begin LNode := LNodeElement.ChildNodes.Get(I); if (LNode <> Nil) AND (LNode.NodeName='Antenna') then begin Memo1.lines.Add('Node name: ' + LNode.NodeName); BNode:=LNode.ChildNodes.FindNode('Mount'); if (BNode <> Nil) then CNode:=BNode.ChildNodes.FindNode('AzEl'); if (CNode <> Nil) then Memo1.lines.Add('found: '+CNode.NodeName) else continue; end; end; end; end; 

CONCLUSION:

 Node name: Antenna Node name: Antenna found: AzEl 
+1
source

What worked for me:

 if (MountNode.ChildNodes.FindNode('AzEl') <> nil) then 

It's not clear how nil responds to setting parameters in a TXMLDocumnet, like doAttrNull , but it works.

0
source

Source: https://habr.com/ru/post/918222/


All Articles