【发布时间】:2016-05-03 13:12:04
【问题描述】:
我正在尝试使用 XDocument 类和 XmlSchemaSet 类来验证 XMl 文件。
XML 文件已经存在,但我只想添加一个由其他几个元素组成的元素,我只想验证这个节点。
以下是 XML 文件的示例。我想验证的是TestConfiguration 节点:
<?xml version="1.0" encoding="ISO-8859-1"?>
<Root>
<AppType>Test App</AppType>
<LabelMap>
<Label0>
<Title>Tests</Title>
<Indexes>1,2,3</Indexes>
</Label0>
</LabelMap>
<TestConfiguration>
<CalculateNumbers>true</CalculateNumbers>
<RoundToDecimalPoint>3</RoundToDecimalPoint>
</TestConfiguration>
</Root>
到目前为止,这是我的 xsd:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="TestConfiguration"
targetNamespace="MyApp_ConfigurationFiles" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="TestConfiguration">
<xs:complexType>
<xs:sequence>
<xs:element name="CalculateNumbers" type="xs:boolean" minOccurs="1" maxOccurs="1"/>
<xs:element name="RoundToDecimalPoint" type="xs:int" minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
这是我用来验证它的代码:
private bool ValidateXML(string xmlFile, string xsdFile)
{
string xsdFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ?? string.Empty, xsdFile);
Logger.Info("Validating XML file against XSD schema file.");
Logger.Info("XML: " + xmlFile);
Logger.Info("XSD: " + xsdFilePath);
try
{
XDocument xsdDocument = XDocument.Load(xsdFilePath);
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(XmlSchema.Read(new StringReader(xsdDocument.ToString()), this.XmlValidationEventHandler));
XDocument xmlDocument = XDocument.Load(xmlFile);
xmlDocument.Validate(schemaSet, this.XmlValidationEventHandler);
}
catch (Exception e)
{
Logger.Info("Error parsing XML file: " + xmlFile);
throw new Exception(e.Message);
}
Logger.Info("XML validated against XSD.");
return true;
}
即使验证完整的 XML 文件,验证也会成功通过,导致当我尝试将 XML 文件加载到由 xsd2code 创建的生成的类文件中时遇到问题,错误:<Root xmlns=''> was not expected.。
如何仅验证 TestConfiguration 部分?
谢谢
【问题讨论】:
-
未知节点是警告,不是错误,所以需要设置
XmlSchemaValidationFlags.ReportValidationWarnings。为此,请参阅XDocument.Validate is always successful。
标签: c# xml validation xsd