In view of the simple structure of your XML, just a series of Car
nodes below a Cars
root node, you can find the maximum existing id
attribute value by iterating the Car
nodes and examining their id
attributes, like this:
Sample project:
type
TForm1 = class(TForm)
Memo1: TMemo;
btnMaxId: TButton;
procedure btnMaxIdClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
public
end;
function MaxId(const XML : String) : Integer;
[...]
var
Form1: TForm1;
implementation
[...]
procedure TForm1.btnMaxIdClick(Sender: TObject);
begin
ShowMessage(IntToStr(MaxID(Memo1.Lines.Text)));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Lines.Add('<Cars>');
Memo1.Lines.Add(' <Car id="1" name="Opel" picture="\File\JPEG\opel.jpg" />');
Memo1.Lines.Add(' <Car id="98" name="Ford" picture="\File\JPEG\ford.jpg" />');
Memo1.Lines.Add(' <Car id="3" name="Volvo" picture="\File\JPEG\volvo.jpg" />');
Memo1.Lines.Add('</Cars>');
end;
function MaxId(const XML : String) : Integer;
var
XmlDoc: IXMLDOMDocument;
NodeList : IXmlDOMNodeList;
Node : IXMLDomNode;
i : Integer;
ID : Integer;
ErrorCode : Integer;
S : String;
begin
Result := 0;
XmlDoc := CoDOMDocument.Create;
try
XmlDoc.Async := False;
XmlDoc.LoadXml(XML);
NodeList := XmlDoc.DocumentElement.childNodes;
for i := 0 to NodeList.Length - 1 do begin
Node := NodeList.item[i];
S := Node.attributes.GetNamedItem('id').nodeValue;
Val(S, ID, ErrorCode);
if ErrorCode = 0 then begin
if ID > Result then
Result := ID;
end;
end;
finally
XmlDoc := Nil;
end;
end;
end.
You need to pass your XML document as a string to this MaxID
function. So, if the XML in your q were in a TMemo component on a form, you could use it like this:
var
NewID : integer;
begin
NewID := 1 + MaxID (Form1.Memo1.Lines.Text);
lNewExpression.id := NewID;
There is a more direct way of getting the maximum value of an attribute, see e.g. How to find the max attribute from an XML document using Xpath 1.0
but that requires some familiarity with XPath queries and you would need to note what it says about getting the maximum value of a multi-character id
.