如何使用C#根据HR-XML验证XML文件
本文关键字:验证 XML 文件 HR-XML 根据 何使用 | 更新日期: 2023-09-27 18:00:09
我正在寻找一些验证HR-XML的建议和指导。
我已经编写了生成XML文件的代码,"应该"正确格式化为HR-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文件中引用了导入的架构,因此生成了异常。错误是未定义的complexType'http://www.openapplications.org/oagis/9:BusinessObjectDocumentType'用作复杂类型扩展的基
将第二个文件添加到架构集中解决了第一个异常,并给出了此异常。类型'http://www.openapplications.org/oagis/9:NormalizedStringType"未声明,或者不是简单类型
我不想做的是在我到达之前添加所有的HR-XML模式文件(除非我真的必须这样做),并在创建的文件中添加"实际"错误。
我是走在正确的轨道上,还是有更好的方法
谢谢。
我发现验证HR-XML的最佳方法是将节点xsi:schemaLocation添加到生成的XML中,该XML指向所需的BOD。
还可以创建一个引用了所有架构文件的XMLSpy项目。如果完成了此操作,则不需要架构位置。