XMLを検証するためにクラスを作成しました。そのクラス内に検証メソッドがあります。XMLスキーマを含む.xsdファイルもあります。このファイルを使用するには、「xsdファイルを文字列にロードする」必要があると言われています。
xsdファイルを文字列にロードするにはどうすればよいですか?
これ以上のコンテキストがなければ、Load the xsd file into a string
実際に何を意味するのかわかりませんが、XMLを検証するためのはるかに簡単な方法があります。
var xDoc = XDocument.Load(xmlPath);
var set = new XmlSchemaSet();
using (var stream = new StreamReader(xsdPath))
{
// the null here is a validation call back for the XSD itself, unless you
// specifically want to handle XSD validation errors, I just pass a null and let
// an exception get thrown as there usually isn't much you can do with an error in
// the XSD itself
set.Add(XmlSchema.Read(stream, null));
}
xDoc.Validate(set, ValidationCallBack);
次に、検証の失敗に対するハンドラーとしてクラスで呼び出されるメソッドが必要ですValidationCallBack
(任意の名前を付けることができますが、Validate()
上記のメソッドがこのメソッドを参照する必要があるパラメーターを委任します)。
public void ValidationCallBack(object sender, ValidationEventArgs e)
{
// do something with any errors
}
このコードで試すことができます
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("....", "youXsd.xsd");
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(YourSettingsValidationEventHandler);
XmlReader books = XmlReader.Create("YouFile.xml", settings);
while (books.Read()) { }
//Your validation
static void YourSettingsValidationEventHandler(object sender, ValidationEventArgs e)
{
}
2ロードするだけの場合は、StreamReaderとReadToEndを使用できます
ファイル全体を文字列に読み込むのは非常に簡単です。
string schema;
using(StreamReader file = new StreamReader(path)
{
schema = file.ReadToEnd();
}
これがあなたの探求に役立つことを願っています。