C#에서 참조된 XSD에 대해 XML 유효성 검사
다음과 같은 지정된 스키마 위치를 가진 XML 파일이 있습니다.
xsi:schemaLocation="someurl ..\localSchemaPath.xsd"
C#에서 검증하고 싶습니다.Visual Studio는 파일을 열면 스키마에 대한 검증을 수행하고 오류를 완벽하게 나열합니다.그러나 어떻게 보면 이렇게 검증할 스키마를 지정하지 않고는 C#에서 자동으로 검증할 수 없을 것 같습니다.
XmlDocument asset = new XmlDocument();
XmlTextReader schemaReader = new XmlTextReader("relativeSchemaPath");
XmlSchema schema = XmlSchema.Read(schemaReader, SchemaValidationHandler);
asset.Schemas.Add(schema);
asset.Load(filename);
asset.Validate(DocumentValidationHandler);
XML 파일에 지정된 스키마로 자동으로 유효성을 확인할 수 있어야 하는 것 아닌가요?제가 무엇을 빠뜨리고 있나요?
XmlReaderSettings 인스턴스를 생성하고 생성할 때 이 인스턴스를 XmlReader에 전달해야 합니다.그러면 가입할 수 있습니다.ValidationEventHandler유효성 검사 오류를 수신하도록 설정합니다.당신의 코드는 결국 다음과 같습니다.
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class ValidXSD
{
public static void Main()
{
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("inlineSchema.xml", settings);
// Parse the file.
while (reader.Read()) ;
}
// Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
사용하는 경우 더 간단한 방법입니다.NET 3.5, 사용 예정XDocument그리고.XmlSchemaSet확인.
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(schemaNamespace, schemaFileName);
XDocument doc = XDocument.Load(filename);
string msg = "";
doc.Validate(schemas, (o, e) => {
msg += e.Message + Environment.NewLine;
});
Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
자세한 지원은 MSDN 설명서를 참조하십시오.
개인적으로 콜백 없이 검증하는 것을 선호합니다.
public bool ValidateSchema(string xmlPath, string xsdPath)
{
XmlDocument xml = new XmlDocument();
xml.Load(xmlPath);
xml.Schemas.Add(null, xsdPath);
try
{
xml.Validate(null);
}
catch (XmlSchemaValidationException)
{
return false;
}
return true;
}
(Synchronous XML Schema Validation의 Timiz0r 게시물 참조?NET 3.5)
다음 예제에서는 XML 파일의 유효성을 검사하고 적절한 오류 또는 경고를 생성합니다.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
public class Sample
{
public static void Main()
{
//Load the XmlSchemaSet.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("urn:bookstore-schema", "books.xsd");
//Validate the file using the schema stored in the schema set.
//Any elements belonging to the namespace "urn:cd-schema" generate
//a warning because there is no schema matching that namespace.
Validate("store.xml", schemaSet);
Console.ReadLine();
}
private static void Validate(String filename, XmlSchemaSet schemaSet)
{
Console.WriteLine();
Console.WriteLine("\r\nValidating XML file {0}...", filename.ToString());
XmlSchema compiledSchema = null;
foreach (XmlSchema schema in schemaSet.Schemas())
{
compiledSchema = schema;
}
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(compiledSchema);
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.ValidationType = ValidationType.Schema;
//Create the schema validating reader.
XmlReader vreader = XmlReader.Create(filename, settings);
while (vreader.Read()) { }
//Close the reader.
vreader.Close();
}
//Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
위의 예에서는 다음 입력 파일을 사용합니다.
<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema" xmlns:cd="urn:cd-schema">
<book genre="novel">
<title>The Confidence Man</title>
<price>11.99</price>
</book>
<cd:cd>
<title>Americana</title>
<cd:artist>Offspring</cd:artist>
<price>16.95</price>
</cd:cd>
</bookstore>
books.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:bookstore-schema"
elementFormDefault="qualified"
targetNamespace="urn:bookstore-schema">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="author" type="authorName"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="authorName">
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string"/>
<xsd:element name="last-name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
VB에서 이런 종류의 자동 유효성 검사를 수행했으며 이렇게 수행했습니다(C#로 변환).
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
XmlReader XMLvalidator = XmlReader.Create(reader, settings);
그 다음에 가입을 했습니다.settings.ValidationEventHandler파일을 읽는 동안 이벤트가 발생합니다.
언급URL : https://stackoverflow.com/questions/751511/validating-an-xml-against-referenced-xsd-in-c-sharp
'IT' 카테고리의 다른 글
| Android에서 사용자 지정 라디오 단추 추가 (0) | 2023.09.20 |
|---|---|
| json과 xml의 장점과 단점은 무엇입니까? (0) | 2023.09.20 |
| 오라클에서 날짜를 2개 빼서 시 분 단위로 결과를 얻는 방법 (0) | 2023.09.20 |
| 이런 C/C++ 농담은 이해가 안 돼요. (0) | 2023.09.20 |
| Git Submodule 포인터를 포함하는 저장소에 저장된 커밋으로 되돌리는 방법은 무엇입니까? (0) | 2023.09.20 |