如何使用delphi检查XML文件是否格式正确? [英] How Check if a XML file if well formed using delphi?
本文介绍了如何使用delphi检查XML文件是否格式正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查没有无效字符或标记的xml文件格式是否正确?
How can I check if a xml file is well formed without invalid chars or tags?
例如,考虑以下xml:
For example, consider this 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
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.
- errorCode 包含最后一个解析错误的错误代码。只读。
- filepos 包含发生错误的绝对文件位置。只读。
- 行指定包含错误的行号。只读。
- linepos 包含发生错误的行中的字符位置。
- 原因描述错误的原因。只读。
- srcText 返回包含错误的行的全文。只读。
- url 包含包含最后一个错误的XML文档的URL。
- errorCode Contains the error code of the last parse error. Read-only.
- filepos Contains the absolute file position where the error occurred. Read-only.
- line Specifies the line number that contains the error. Read-only.
- linepos Contains the character position within the line where the error occurred.
- reason Describes the reason for the error. Read-only.
- srcText Returns the full text of the line containing the error. Read-only.
- url Contains the URL of the XML document containing the last error. Read-only.
检查这两个使用MSXML 6.0的功能(也可以使用其他版本)
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;
这篇关于如何使用delphi检查XML文件是否格式正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文