ワープロ ドキュメントを検証する
このトピックでは、Open XML SDK for Office のクラスを使用して、プログラムによってワープロ ドキュメントを検証する方法について説明します。
サンプル コードの動作のしくみ
このコード例は、2 つのメソッドで構成されます。 最初のメソッド ValidateWordDocument は、通常のWord ファイルを検証するために使用されます。 これは例外をスローせず、検証チェックを実行した後にファイルを閉じます。 2 番目のメソッド ValidateCorruptedWordDocument は、テキストを本文に挿入することから始まり、スキーマ エラーが発生します。 次に、Word ファイルを検証します。その場合、メソッドは破損したファイルを開こうとしたときに例外をスローします。 検証は、 Validate メソッドを使用して行われます。 コードには、エラーの数に加えて、検出されたすべてのエラーに関する情報が表示されます。
重要
[!重要] なお、このコードは、最初の実行でファイルが壊れると 2 回目の実行ができません。 その場合は、新しい Word ファイルを使用して実行し直す必要があります。
以下は、C# および Visual Basic の完全なサンプル コードです。
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
static void ValidateWordDocument(string filepath)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
{
try
{
OpenXmlValidator validator = new OpenXmlValidator();
int count = 0;
foreach (ValidationErrorInfo error in
validator.Validate(wordprocessingDocument))
{
count++;
Console.WriteLine("Error " + count);
Console.WriteLine("Description: " + error.Description);
Console.WriteLine("ErrorType: " + error.ErrorType);
Console.WriteLine("Node: " + error.Node);
if (error.Path is not null)
{
Console.WriteLine("Path: " + error.Path.XPath);
}
if (error.Part is not null)
{
Console.WriteLine("Part: " + error.Part.Uri);
}
Console.WriteLine("-------------------------------------------");
}
Console.WriteLine("count={0}", count);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
static void ValidateCorruptedWordDocument(string filepath)
{
// Insert some text into the body, this would cause Schema Error
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(filepath, true))
{
if (wordprocessingDocument.MainDocumentPart is null || wordprocessingDocument.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Insert some text into the body, this would cause Schema Error
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
Run run = new Run(new Text("some text"));
body.Append(run);
try
{
OpenXmlValidator validator = new OpenXmlValidator();
int count = 0;
foreach (ValidationErrorInfo error in
validator.Validate(wordprocessingDocument))
{
count++;
Console.WriteLine("Error " + count);
Console.WriteLine("Description: " + error.Description);
Console.WriteLine("ErrorType: " + error.ErrorType);
Console.WriteLine("Node: " + error.Node);
if (error.Path is not null)
{
Console.WriteLine("Path: " + error.Path.XPath);
}
if (error.Part is not null)
{
Console.WriteLine("Part: " + error.Part.Uri);
}
Console.WriteLine("-------------------------------------------");
}
Console.WriteLine("count={0}", count);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}