問題描述
我正在使用一些在 xml 中形成元素的 xml 'snippets'.我有架構,但我無法驗證這些文件,因為它們不是完整的 xml 文檔.這些片段包含必要的父元素以在其他工具中使用它們時形成有效的 xml,因此我沒有太多選擇將它們變成有效的 xml 或更改架構.
I'm working with some xml 'snippets' that form elements down the xml. I have the schema but I cannot validate these files because they are not complete xml documents. These snippets are wrapped with the necessary parent elements to form valid xml when they are used in other tools so I don't have much option in making them into valid xml or in changing the schema.
是否可以驗證一個元素,而不是整個文檔?如果沒有,可以建議哪些解決方法?
Is it possible to validate an element, rather than the whole document? If not, what workarounds could be suggested?
我正在使用帶有 .NET 2.0 框架的 C#.
I'm working in C# with .NET 2.0 framework.
推薦答案
我遇到了類似的問題,我只能驗證部分 XML 文檔.我在這里想出了這個方法:
I had a similar problem where I could only validate parts of my XML document. I came up with this method here:
private void ValidateSubnode(XmlNode node, XmlSchema schema)
{
XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.Schemas.Add(schema);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(XSDValidationEventHandler);
using (XmlReader validationReader = XmlReader.Create(reader, settings))
{
while (validationReader.Read())
{
}
}
}
private void XSDValidationEventHandler(object sender, ValidationEventArgs args)
{
errors.AppendFormat("XSD - Severity {0} - {1}",
args.Severity.ToString(), args.Message);
}
基本上,我將一個 XmlNode(我通過 .SelectSingleNode 從整個 XmlDocument 中選擇)和一個?? XML 模式傳遞給它,我從我的應用程序內的嵌入式資源 XSD 加載它.任何可能發生的驗證錯誤都被填充到錯誤"字符串構建器中,然后我在最后讀出它,看看是否記錄了任何錯誤.
Basically, I pass it an XmlNode (which I select from the entire XmlDocument by means of .SelectSingleNode), and an XML schema which I load from an embedded resource XSD inside my app. Any validation errors that might occur are being stuffed into a "errors" string builder, which I then read out at the end, to see if there were any errors recorded, or not.
為我工作 - 你的里程可能會有所不同:-)
Works for me - your mileage may vary :-)
這篇關于驗證 xml 節點,而不是整個文檔的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!