如何检查 xml 文件是否格式正确且没有无效字符或标签?
例如,考虑这个 xml:
<?xml version="1.0"?>
<PARTS>
<TITLE>Computer Parts</TITLE>
<PART>
<ITEM>Motherboard</ITEM>
<MANUFACTURER>ASUS</MANUFACTURER>
<MODEL>P3B-F</MODEL>
<COST> 123.00</COST>
</PART>
<PART>
<ITEM>Video Card</ITEM>
<MANUFACTURER>ATI</MANUFACTURER>
<MODEL>All-in-Wonder Pro</MODEL>
<COST> 160.00</COST>
</PART>
</PARTSx>
最后一个标签</PARTSx>
必须是 </PARTS>
最佳答案
您可以使用 IXMLDOMParseError
MSXML DOMDocument
返回的接口(interface)
此接口(interface)返回一系列属性,可帮助您识别问题。
- errorCode 包含最后一次解析错误的错误代码。只读。
- filepos 包含发生错误的绝对文件位置。只读。
- line 指定包含错误的行号。只读。
- linepos 包含行中发生错误的字符位置。
- reason 描述错误的原因。只读。
- srcText 返回包含错误的行的完整文本。只读。
- url 包含包含最后一个错误的 XML 文档的 URL。只读。
检查这两个使用MSXML 6.0的函数(您也可以使用其他版本)
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;
关于xml - 如何使用 Delphi 检查 XML 文件是否格式正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520572/