如何用C#代码验证XML文件是否符合DTD规范
其实在网上可以搜索到相关代码,但是大部分网上找到的代码只适用于较低版本的Framework,如果你使用的Framework版本较高,用网上常见的代码来验证包含外部dtd引用的xml是验证通不过的。以下是正确的代码:
internal class Program
{
static void Main(string[] args)
{
if (!Validate(@"e:\xml\引用dtd文件的xml.xml", out string errorMessage))
{
Console.WriteLine(errorMessage);
}
else
{
Console.WriteLine("That's ok");
}
Console.ReadLine();
}
static bool Validate(string xmlFile, out string errorMessage)
{
errorMessage = String.Empty;
var sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Parse,
ValidationType = ValidationType.DTD,
XmlResolver = new XmlUrlResolver() // 注意这里,没有这句的话无法验证引用了外部dtd的xml文件
};
settings.ValidationEventHandler += (s, e) => { sb.Append($"-\n{e.Message}"); };
try
{
using (var reader = XmlReader.Create(xmlFile, settings))
{
while (reader.Read()) ;
}
}
catch (Exception ex)
{
sb.Append(ex.Message);
}
if (sb.Length > 0)
{
errorMessage = sb.ToString();
}
return sb.Length == 0;
}
}
附上3个示例文件:
自包含dtd的xml.xml:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<body>D
引用dtd文件的xml.xml
<!--XML file using a DTD-->
<!DOCTYPE store SYSTEM "dtd文件.dtd">
<store>
<item type="supplies">
<name>paint</name>
<price>16.95</price>
</item>
</store>
dtd文件.dtd:
<!ELEMENT store (item)*>
<!ELEMENT item (name,price)>
<!ATTLIST item type CDATA #REQUIRED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
欢迎转载,转载请注明出处