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 回答