【问题标题】:How to use xmlDocument to check if certain attributes of the document exist如何使用 xmlDocument 检查文档的某些属性是否存在
【发布时间】:2015-05-05 00:30:44
【问题描述】:

所以我正在尝试检查文档是否具有某些属性。例如,我有一篇硕士论文样本,我必须检查的一件事是标题是否以标题页为中心。到目前为止,我已经创建了 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# 中。任何帮助将不胜感激。

【问题讨论】:

    标签: c# xml openxml openxml-sdk wordprocessingml


    【解决方案1】:

    .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 -&gt; w:pgSz -&gt; 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>();
    

    我不太了解这部分,但我想您可以获得所需的所有信息,只需阅读文档即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 2012-04-16
      • 2012-07-12
      • 2018-08-04
      • 1970-01-01
      相关资源
      最近更新 更多