openxml - 如何以编程方式访问打开的xml word doc文件的内置属性

标签 openxml openxml-sdk

我想访问一个打开的xml word文档文件的一些内置属性(例如作者,最后修改日期等)。我想为此使用开放的xml sdk2.0。所以我想知道是否有任何类或任何方式可以以编程方式访问这些内置属性。

最佳答案

可以在here中找到以下方法的说明,但是几乎您需要将要从core.xml文件中获取的属性传递给该方法,它将返回该值:

public static string WDRetrieveCoreProperty(string docName, string propertyName)
{
   // Given a document name and a core property, retrieve the value of the property.
   // Note that because this code uses the SelectSingleNode method, 
   // the search is case sensitive. That is, looking for "Author" is not 
   // the same as looking for "author".

   const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
   const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
   const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";

   string propertyValue = string.Empty;

   using (WordprocessingDocument wdPackage = WordprocessingDocument.Open(docName, true))
   {
      // Get the core properties part (core.xml).
      CoreFilePropertiesPart corePropertiesPart = wdPackage.CoreFilePropertiesPart;

      // Manage namespaces to perform XML XPath queries.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("cp", corePropertiesSchema);
      nsManager.AddNamespace("dc", dcPropertiesSchema);
      nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);

      // Get the properties from the package.
      XmlDocument xdoc = new XmlDocument(nt);

      // Load the XML in the part into an XmlDocument instance.
      xdoc.Load(corePropertiesPart.GetStream());

      string searchString = string.Format("//cp:coreProperties/{0}", propertyName);

      XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
      if (!(xNode == null))
      {
         propertyValue = xNode.InnerText;
      }
   }

   return propertyValue;
}

关于openxml - 如何以编程方式访问打开的xml word doc文件的内置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4433810/

相关文章:

c# - 在 Open XML 2.0 中打开一个 microsoft .xml 文件并添加变量数据

java - 在 Docx4j 生成的 Word 文档的页眉中显示图像

algorithm - 从 Excel 导入中查找包含的边界区域

c# - Open XML SDK 读取大型 excel 文件的性能如何?

c# - 使用 Open XML 从 Excel 到 C# 中的 DataTable

C# OpenXML SDK - 从幻灯片母版插入新幻灯片

c# - OpenXML:用 WordprocessingML 中的表替换 <sdt/> 元素

c# - 打开 Office xml SDK 异常 "Cannot insert the OpenXmlElement "newChild“因为它是树的一部分”

C# OpenXML 如何从 Cell 获取超链接

c# - Openxml:使用自定义属性添加新行