我有一个xml文件,我使用DataSet.ReadXML在DataTable中加载它。此XML具有内部DTD定义。我认为DataTable.ReadXML在将XML加载到内存之前验证XML。是这样的吗?
我是否需要在我的数据集中设置一些属性以使其针对定义的DTD验证Xml,或者我是否需要使用其他XML类验证它
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE Resources [
<!ELEMENT Resources (Resource)+>
<!ELEMENT Resource (ResourceName,ResourceEmail)>
<!ELEMENT ResourceName (#PCDATA)>
<!ELEMENT ResourceEmail (#PCDATA)>
]>
<Resources>
<Resource>
<ResourceName>test</ResourceName>
<ResourceEmail>dfjfhg@fkjg.com</ResourceEmail>
</Resource>
</Resources>
答案 0 :(得分:0)
您需要将XmlReadMode枚举与ReadXML方法一起使用:
DataSet.ReadXml(Stream|String|TextReader|XmlReader, XmlReadMode.ReadSchema)
e.g。
string xml = // your xml here; can also use Stream, TextReader or XmlReader
DataSet.ReadXml(xml, XmlReadMode.ReadSchema);
已添加
如果您希望验证 XML,则需要使用XmlReader并创建“验证”阅读器。看一下这篇文章:
答案 1 :(得分:0)
var errors = new StringBuilder();
var isValid = true;
var settings = new XmlReaderSettings();
settings.ValidationEventHandler += (o, e) => { errors.AppendLine(e.Message); isValid = false; };
settings.ValidationType = ValidationType.DTD;
settings.DtdProcessing = DtdProcessing.Parse;
var content = @"<?xml version=""1.0"" standalone=""yes""?>
<!DOCTYPE Resources [
<!ELEMENT Resources (Resource)+>
<!ELEMENT Resource (ResourceName,ResourceEmail)>
<!ELEMENT ResourceName (#PCDATA)>
<!ELEMENT ResourceEmail (#PCDATA)>
]>
<Resources>
<Resource>
<ResourceName>test</ResourceName>
<ResourceEmail>dfjfhg@fkjg.com</ResourceEmail>
<YourPlaceIsNotHere>asdasd</YourPlaceIsNotHere>
</Resource>
</Resources>";
using (var validator = XmlReader.Create(new StringReader(content), settings))
{
while (validator.Read())
{
if (!isValid)
{
validator.Close();
break;
}
}
}
解决方案是使用此代码在加载到DataSet之前验证xml。
答案 2 :(得分:0)
您可以使用此代码根据DTD验证XML
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.DTD;
string data = null;
XmlReader validatingReader = XmlReader.Create(File.Open("C:\\check\\TEMP_DTD.XML", FileMode.Open), settings, data);
DataSet ds = new DataSet();
ds.ReadXml(validatingReader);