Remove specific XML element in Delphi

6.8k views Asked by At

I have an xml document looks like this:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ExtensionData />
  <Name>ali</Name>
  <Age>37</Age>
  <Father>
    <ExtensionData />
    <Name>I</Name>
    <Age>72</Age>
  </Father>
  <Mother>
    <ExtensionData />
    <Name>M</Name>
    <Age>62</Age>
  </Mother>
</Person>

I am using Delphi 7.

How can I remove all ExtensionData elements in XML document like this?

1

There are 1 answers

5
Remy Lebeau On BEST ANSWER

You can use the IXMLNodeList.Delete() or IXMLNodeList.Remove() method to remove nodes:

var
  Root: IXMLNode;
begin
  Root := XMLDocument1.DocumentElement;
  Root.ChildNodes.Delete('ElementData');
  for I := 0 to Root.ChildNodes.Count-1 do
    Root.ChildNodes[I].ChildNodes.Delete('ElementData');
end;

var
  Root, Child, Node: IXMLNode;
begin
  Root := XMLDocument1.DocumentElement;
  Node := Root.ChildNodes.FindNode('ElementData');
  if Node <> nil then Root.ChildNodes.Remove(Node);
  for I := 0 to Root.ChildNodes.Count-1 do
  begin
    Child := Root.ChildNodes[I];
    Node := Child.ChildNodes.FindNode('ElementData');
    if Node <> nil then Child.ChildNodes.Remove(Node);
  end;
end;

If you want to remove all ElementData elements regardless of their depth within the document, a recursive procedure can do that:

procedure RemoveElementData(Node: IXMLNode);
var
  Root, Child: IXMLNode;
begin
  repeat until Node.ChildNodes.Delete('ElementData') = -1;
  for I := 0 to Node.ChildNodes.Count-1 do
    RemoveElementData(Node.ChildNodes[I]);
  end;
end;

begin
  RemoveElementData(XMLDocument1.DocumentElement);
end;