我有一个复杂的架构结构,使用标签有多个架构。我遇到的问题是访问存储在子文件夹中的模式文件(类似于/xsd/Person/personcommon.xsd),因为添加为嵌入式资源时文件结构不存在。我编写了一个.dll来验证XML文件,然后将文件反序列化为对象。这些对象由另一个应用程序调用。在搜索之后,我想出了以下内容来帮助验证XML:
public bool ValidateXML(string xmlFilePath)
{
// Set the namespace followed by the folder
string prefix = "MyApp.xsd";
// Variable to determine if file is valid
bool isValid = true;
// Assembly object to find the embedded resources
Assembly myAssembly = Assembly.GetExecutingAssembly();
// Get all the xsd resoruces
var resourceNames = myAssembly.GetManifestResourceNames().Where(name => name.StartsWith(prefix));
try
{
// Load the XML
XDocument xmlDoc = XDocument.Load(xmlFilePath);
// Create new schema set
XmlSchemaSet schemas = new XmlSchemaSet();
// Iterate through all the resources and add only the xsd's
foreach (var name in resourceNames)
{
using (Stream schemaStream = myAssembly.GetManifestResourceStream(name))
{
using (XmlReader schemaReader = XmlReader.Create(schemaStream))
{
schemas.Add(null, schemaReader);
}
}
}
// Call to the validate method
xmlDoc.Validate(schemas, (o, e) => { this.ErrorMessage = string.Format("File failure: There was an error validating the XML document: {0} ", e.Message); isValid = false; }, true);
return isValid;
}
catch (Exception ex)
{
isValid = false;
this.ErrorMessage = string.Format("File failure: There was an error validating the XML document: {0}", ex.ToString());
return isValid;
}
}
我现在遇到的问题是我的单元测试。通过代码解析我看到在调用schemas.Add()时抛出异常,它无法找到引用的XSD文件。奇怪的是它仍然验证正确传递的XML文件。
这是预期的行为吗?我编写的代码是否有效/是否有更好的方法可以访问这些XSD文件。