1

そのため、ドキュメントに特定の属性があるかどうかを確認しようとしています。たとえば、修士論文のサンプルがあり、チェックしなければならないことの 1 つは、タイトルがタイトル ページの中央に配置されているかどうかです。ここまでで、docx ファイルの xmlDocument オブジェクトを作成して、その Xml にアクセスできるようにしました。そのためのコードは

public void ProcessDocument(string documentFullPath){
        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(documentFullPath, true)){
            NameTable table = new NameTable();
            XmlNamespaceManager xnm = new XmlNamespaceManager(table);
            xnm.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingxml/2006/main");

            XmlDocument tempDoc = new XmlDocument();

            tempDoc.LoadXml(myDoc.MainDocumentPart.Document.InnerXml);

        }
    }

私の質問は: ドキュメントの xml にアクセスし、探している属性がドキュメントに含まれているかどうかを確認する最も効率的な方法は何ですか? xml を文字列に変換して正規表現を使用するか、それともより効率的な方法を実行するか? 私のコードはC#です。どんな助けでも大歓迎です。

4

1 に答える 1

0

.NET には、XML を読み取るいくつかの手法があります。LINQ to XMLを使用することをお勧めします。簡単な Word ファイルとドキュメント XML を作成したのは次のとおりです。

<?xml version="1.0" encoding="UTF-8"?>
<w:body xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
   <w:p w:rsidR="002039FC" w:rsidRDefault="00014532">
      <w:r>
         <w:t xml:space="preserve">La </w:t>
      </w:r>
      <w:proofErr w:type="spellStart" />
      <w:r>
         <w:t>la</w:t>
      </w:r>
      <w:proofErr w:type="spellEnd" />
      <w:r>
         <w:t xml:space="preserve"> la</w:t>
      </w:r>
      <w:bookmarkStart w:name="_GoBack" w:id="0" />
      <w:bookmarkEnd w:id="0" />
   </w:p>
   <w:sectPr w:rsidR="002039FC">
      <w:pgSz w:w="11906" w:h="16838" />
      <w:pgMar w:top="1417" w:right="1134" w:bottom="1417" w:left="1134" w:header="708" w:footer="708" w:gutter="0" />
      <w:cols w:space="708" />
      <w:docGrid w:linePitch="360" />
   </w:sectPr>
</w:body>

の値を読み取りたい場合は、次のw:sectPr -> w:pgSz -> w:wようなコードを記述できます。

using (var doc = WordprocessingDocument.Open("docx_path", false))
{
    XNamespace wNs = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    var xml = XElement.Parse(doc.MainDocumentPart.Document.InnerXml);

    var pageWidth = xml
        .Element(wNs + "sectPr")
        .Element(wNs + "pgSz")
        .Attribute(wNs + "w")
        .Value;
}

Open XML ドキュメントを読み取る (および変更する) 方法は他にもあります。DocumentFormat.OpenXml名前空間を確認できます。型付けされた方法で XML にアクセスできます。たとえば、ドキュメント内のすべての段落を取得するには、次のようにします。

IEnumerable<Paragraph> paragraphs = 
    doc.MainDocumentPart.Document.Body.Elements<Paragraph>();

この部分はよくわかりませんが、ドキュメントを読むだけで必要なすべての情報を取得できると思います。

于 2015-05-05T09:44:51.407 に答える