如何检查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>
Run Code Online (Sandbox Code Playgroud)
最后一个标签</PARTSx>必须是</PARTS>
RRU*_*RUZ 13
您可以使用IXMLDOMParseError返回的界面MSXML DOMDocument
此界面返回一系列属性,可帮助您识别问题.
检查这两个使用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;
Run Code Online (Sandbox Code Playgroud)
你是如何创建/接收XML的?任何明智的解析器都会抓住这个.
例如,使用OmniXML
uses
OmniXML;
type
TForm1=class(TForm)
Memo1: TMemo;
//...
private
FXMLDoc: IXMLDocument;
procedure FormCreate(Sender: TObject);
procedure CheckXML;
end;
implementation
uses
OmniXMLUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
// Load your sample XML. Can also do Memo1.Text := YourXML
Memo1.Lines.LoadFromFile('YourXMLFile.xml');
end;
procedure TForm1.CheckXML;
begin
FXMLDoc := CreateXMLDoc;
// The next line raises an exception with your sample file.
XMLLoadFromAnsiString(FXMLDoc, Memo1.Text);
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3923 次 |
| 最近记录: |