【发布时间】:2011-06-21 15:36:37
【问题描述】:
我正在寻找一些关于验证 HR-XML 的建议和指导。
我已经编写了代码来生成一个“应该”正确格式化为 HR-XML 的 XML 文件,但我想在编写之前使用代码对其进行验证到磁盘。
下面是我的验证方法和验证错误事件处理程序的代码示例
/// <summary>
/// Validate the populated XML
/// </summary>
/// <remarks>
/// The schema folder needs to be "HR-XML-3_0" which contains the "org_hr-xml" and "org_openapplications_platform" folders
/// </remarks>
/// <param name="schemaPath">The root path for the HR-XML XSD files for the xml to be validated against</param>
/// <returns>true if the xml is valid, else false</returns>
public bool Validate(string schemaPath)
{
try
{
// Initalise the valid flag
this.m_FormatValid = false;
this.m_ValidationErrors.Clear();
// Check if there is anything to output
if (this.m_Root.HasElements == true)
{
// Validate that the root node has been populated correctly
XDocument doc = new XDocument(m_Root);
XmlSchemaSet schemas = new XmlSchemaSet();
// Add the schemas in the specified folder to the schema set
schemas.Add(XmlSchema.Read(new StreamReader(Path.Combine(schemaPath, @"org_hr-xml\3_0\Developer\BODs\RespondHRMasterData.xsd")), null));
schemas.Add(XmlSchema.Read(new StreamReader(Path.Combine(schemaPath, @"org_openapplications_platform\1_1\Common\OAGi\Components\Meta.xsd")), null));
// Set the valid flag to true prior to validation and let the event handler set it to false if it's not valid
this.m_FormatValid = true;
doc.Validate(schemas, HRXML_Validation_Error);
}
else
{
Log.WriteLine(Category.Info, "No HR-XML data to validate");
}
}
catch (Exception ex)
{
this.m_FormatValid = false;
Log.WriteLine(Category.Warning, "An error was detected whilst validating HR-XML data", ex);
}
return this.m_FormatValid;
}
/// <summary>
/// Event handler for XML validation errors
/// </summary>
void HRXML_Validation_Error(Object source, ValidationEventArgs args)
{
// There is no need to worry about the severity of the validation as they should always be errors
// The warning appears only to be triggered is no schema has been specified which shouyldn't be the case here
// Output the message to the validation list
this.m_ValidationErrors.Add( args.Message );
//Set the Valid flag to false
m_FormatValid = false;
}
我将用于响应 HRMasrterData 请求的 BOD 添加到架构集中,但由于 RespondHRMasterData.xsd 文件中引用了导入的架构,这会产生异常。错误是 Undefined complexType 'http://www.openapplications.org/oagis/9:BusinessObjectDocumentType' 用作复杂类型扩展的基础。
将第二个文件添加到模式集中解决了第一个异常并给出了这个异常。 类型 'http://www.openapplications.org/oagis/9:NormalizedStringType' 未声明,或者不是简单类型。
我不应该做的是在创建文件中添加所有 HR-XML 架构文件(除非我真的必须这样做)并在创建的文件中出现“实际”错误。
我是在正确的轨道上还是有更好的方法?
谢谢。
【问题讨论】:
-
我创建的 xml 将使用项目在 XML-SPY 中很好地验证。如果我将 xsi:schemaLocation 属性添加到带有 RespondHRMasterData.xsd 路径的根节点,它也会正确验证。
标签: c# xml validation