問題描述
我需要實現一個 C# 方法,該方法需要針對外部 XSD 驗證 XML 并返回一個布爾結果,指示它是否格式正確.
I need to implement a C# method that needs to validate an XML against an external XSD and return a Boolean result indicating whether it was well formed or not.
public static bool IsValidXml(string xmlFilePath, string xsdFilePath);
我知道如何使用回調進行驗證.我想知道它是否可以在一個方法中完成,而不使用回調.我需要這個純粹是為了美觀:我需要驗證多達幾十種類型的 XML 文檔,所以我想做如下簡單的事情.
I know how to validate using a callback. I would like to know if it can be done in a single method, without using a callback. I need this purely for cosmetic purposes: I need to validate up to a few dozen types of XML documents so I would like to make is something as simple as below.
if(!XmlManager.IsValidXml(
@"ProjectTypesProjectType17.xml",
@"SchemasProject.xsd"))
{
throw new XmlFormatException(
string.Format(
"Xml '{0}' is invalid.",
xmlFilePath));
}
推薦答案
根據您是否要對非異常事件使用異常,我可以想到幾個選項.
There are a couple of options I can think of depending on whether or not you want to use exceptions for non-exceptional events.
如果你傳遞一個 null 作為驗證回調委托,如果 XML 格式錯誤,大多數內置驗證方法都會拋出異常,因此你可以簡單地捕獲異常并返回 true
/false
視情況而定.
If you pass a null as the validation callback delegate, most of the built-in validation methods will throw an exception if the XML is badly formed, so you can simply catch the exception and return true
/false
depending on the situation.
public static bool IsValidXml(string xmlFilePath, string xsdFilePath, XNamespace namespaceName)
{
var xdoc = XDocument.Load(xmlFilePath);
var schemas = new XmlSchemaSet();
schemas.Add(namespaceName, xsdFilePath);
try
{
xdoc.Validate(schemas, null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
想到的另一個選項是在不使用回調 標準的情況下突破的限制.除了傳遞預定義的回調方法,您還可以傳遞一個匿名方法并使用它來設置
true
/false
返回值.
The other option that comes to mind pushes the limits of your without using a callback
criterion. Instead of passing a pre-defined callback method, you could instead pass an anonymous method and use it to set a true
/false
return value.
public static bool IsValidXml(string xmlFilePath, string xsdFilePath, XNamespace namespaceName)
{
var xdoc = XDocument.Load(xmlFilePath);
var schemas = new XmlSchemaSet();
schemas.Add(namespaceName, xsdFilePath);
Boolean result = true;
xdoc.Validate(schemas, (sender, e) =>
{
result = false;
});
return result;
}
這篇關于通過單一方法針對 XSD 驗證 XML的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!