Lazarus Reading XML- with TXMLDocument and TXPathVariable
也就是使用XPath的方式,具体语法规则查看http://www.w3school.com.cn/xpath/xpath_syntax.asp,说明得相当详细。这里列举例子是说明在Lazarus/FPC下具体应用于实现,以及注意事项。首先可以构建一个“ReadXPath”的函数方便调用。毕竟每次使用EvaluateXPathExpression后还有些任务要处理……。
- function ReadXPath(const aNode: TDOMNode; const aPath: string): TDOMNode;
- var
- rv: TXPathVariable;
- tl: TFPList;
- begin
- Result := nil;
- if Assigned(aNode) then
- begin
- rv := EvaluateXPathExpression(aPath, aNode);
- if Assigned(rv) then
- begin
- tl := rv.AsNodeSet;
- if Assigned(tl) then
- begin
- if tl.Count > 0 then
- begin
- Result := TDOMNode(tl[0]);
- end;
- end;
- end;
- end;
- end;
具体使用了,要记住返回的其实是“元素”,就算强制约定了“属性”——[@Attrib],所以要读取任何值,都要按“扫描到元素”的方式来处理。
- function ReadCFG: boolean;
- var
- .....
- vConfigXml: string = '';
- HistoryPath: string = '';
- TracePath: string = '';
- vXP: TDOMNode;
- .....
- begin
- Result := False;
- ReadXMLFile(xmlCfg, vConfigXml);
- vXP := ReadXPath(xmlCfg, '/Config/HistoryPath[@value]');
- if Assigned(vXP) then
- begin
- if vXP.HasAttributes then
- HistoryPath := vXP.Attributes.Item[0].NodeValue;
- end;
- vXP := ReadXPath(xmlCfg, '/Config/TracePath[@value]');
- if Assigned(vXP) then
- begin
- if vXP.HasAttributes then
- TracePath := vXP.Attributes.Item[0].NodeValue;
- end;
- if (HistoryPath <> '') and (TracePath <> '') then
- .....
- end;