How can I check if a xml file is well formed without invalid chars or tags?
For example, consider this xml:
You can use the IXMLDOMParseError interface returned by the MSXML DOMDocument
this interface return a serie of properties which help you to identify the problem.
check these two functions which uses the MSXML 6.0 (you can use another versions as well)
uses
Variants,
Comobj,
SysUtils;
function IsValidXML(const XmlStr :string;var ErrorMsg:string) : Boolean;
var
XmlDoc : OleVariant;
begin
XmlDoc := CreateOleObject('Msxml2.DOMDocument.6.0');
try
XmlDoc.Async := False;
XmlDoc.validateOnParse := True;
Result:=(XmlDoc.LoadXML(XmlStr)) and (XmlDoc.parseError.errorCode = 0);
if not Result then
ErrorMsg:=Format('Error Code : %s Msg : %s line : %s Character Position : %s Pos in file : %s',
[XmlDoc.parseError.errorCode,XmlDoc.parseError.reason,XmlDoc.parseError.Line,XmlDoc.parseError.linepos,XmlDoc.parseError.filepos]);
finally
XmlDoc:=Unassigned;
end;
end;
function IsValidXMLFile(const XmlFile :TFileName;var ErrorMsg:string) : Boolean;
var
XmlDoc : OleVariant;
begin
XmlDoc := CreateOleObject('Msxml2.DOMDocument.6.0');
try
XmlDoc.Async := False;
XmlDoc.validateOnParse := True;
Result:=(XmlDoc.Load(XmlFile)) and (XmlDoc.parseError.errorCode = 0);
if not Result then
ErrorMsg:=Format('Error Code : %s Msg : %s line : %s Character Position : %s Pos in file : %s',
[XmlDoc.parseError.errorCode,XmlDoc.parseError.reason,XmlDoc.parseError.Line,XmlDoc.parseError.linepos,XmlDoc.parseError.filepos]);
finally
XmlDoc:=Unassigned;
end;
end;