C#とOpen XML SDKを使用して、プログラムで特定のテキストによってWord文書を2つに分割したいと思います。最初の部分で行ったことは、目的のテキストを含む段落までのすべての段落を削除することです。これはうまくいきました。次に、元のドキュメントのコピーで、今回だけ同じことを行い、目的のテキストを含む段落から始まるすべての段落を削除しました。何らかの理由で、2番目の部分は無効なドキュメントであることが判明しました。これはwordを使用して開くことはできません。「OpenXMLSDK2.0 Productivity Tool」で破損したドキュメントを開いて検証しても、ドキュメントの問題は検出されません。
これは、目的のテキストの前の部分を削除するコードです(正常に機能します)。
public static void DeleteFirstPart(string docName)
{
using (WordprocessingDocument document = WordprocessingDocument.Open(docName, true))
{
DocumentFormat.OpenXml.Wordprocessing.Document doc = document.MainDocumentPart.Document;
List<Text> textparts = document.MainDocumentPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().ToList();
foreach (Text textfield in textparts)
{
if (!textfield.Text.Contains("split here"))
{
RemoveItem1(textfield);
}
else
{
break;
}
}
}
}
2つの異なるアイテムの削除メソッドを試しましたが、どちらも同じ結果になりました。
private static void RemoveItem1(Text item)
{
// Need to go up at least two levels to get to the run.
if ((item.Parent != null) &&
(item.Parent.Parent != null) &&
(item.Parent.Parent.Parent != null))
{
var topNode = item.Parent.Parent;
var topParentNode = item.Parent.Parent.Parent;
if (topParentNode != null)
{
topNode.Remove();
// No more children? Remove the parent node, as well.
if (!topParentNode.HasChildren)
{
topParentNode.Remove();
}
}
}
}
private static void RemoveItem2(Text textfield)
{
if (textfield.Parent != null)
{
if (textfield.Parent.Parent != null)
{
if (textfield.Parent.Parent.Parent != null)
{
textfield.Parent.Parent.Remove();
}
else
{
textfield.Parent.Remove();
}
}
else
{
textfield.Remove();
}
}
}
これは、目的のテキストから始まる部分を削除するコードです(ドキュメントを破損します)。
public static void DeleteSecondPart(string docName)
{
using (WordprocessingDocument document = WordprocessingDocument.Open(docName, true))
{
DocumentFormat.OpenXml.Wordprocessing.Document doc = document.MainDocumentPart.Document;
List<Text> textparts = document.MainDocumentPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().ToList();
bool remove = false;
foreach (Text textfield in textparts)
{
if (textfield.Text.Contains("split here"))
{
remove = true;
}
if(remove)
{
RemoveItem1(textfield);
//Using this commented code line, instead of the one above, removes only the text field itself, it works fine, the document is valid, but it leaves empty paragraphs that could be pages long.
//textfield.Remove();
}
}
}
}