为 OpenXML 文档中的新书签定义正确的 ID

Defining correct ids for new bookmarks in OpenXML document

我正在编写一个 POC 应用程序,我希望能够在其中根据各种条件在 Word 文档中动态创建书签。

到目前为止,我已经设法实际创建和添加 BookmarkStart 和 BookmarkEnd 元素,但我正在尝试弄清楚 'Id' 属性 应该如何设置。

在这方面我能找到的唯一规范是来自 MSDN 的 BookmarkStart 元素示例:

id (Annotation Identifier)
Specifies a unique identifier for an annotation within a WordprocessingML document. The restrictions on the id attribute, if any, are defined by the parent XML element.
If this attribute is omitted, then the document is non-conformant.
[Example: Consider an annotation represented using the following WordprocessingML fragment:
<… w:id="1" … >

</…>
The id attribute specifies that the ID of the current annotation is 1. This value is used to uniquely identify this annotation within the document content. end example]
The possible values for this attribute are defined by the ST_DecimalNumber simple type (§17.18.10).

所以,我知道它必须是一个数字,这是强制性的,而且 ID 必须是唯一的(呃!)。现在,它应该只在书签元素之间或在定义 id 的所有元素之间是唯一的吗?我应该如何制作这样的身份证件?我正在考虑使用 Linq 将所有 id 获取为数值(整数?对我来说 "Decimal" 意味着浮点数)然后将 1 加到最大值,但这似乎有点极端。

到目前为止,我的解决方案包含以下功能:

private static string ComputeNewId(OpenXmlElement root)
{
    return ((from b in root.Descendants<BookmarkStart>() select Decimal.Parse(b.Id)).Max() + 1).ToString();
}

到目前为止,它似乎在工作,但老实说,我不知道这在长期 运行 中是否会可靠,因此非常欢迎提供有关此的任何其他信息。

谢谢大家。

我会尝试依次回答您的每个问题:

is it supposed to be unique only between bookmark elements, or between all elements defining an id?

Id 只需要在 BoookmarkStart 个元素中是唯一的。一个 BookmarkStart 必须 有一个对应的 BookmarkEnd 具有相同的 Id 否则文档不兼容。

§17.13.6.2 书签开始状态:

This element specifies the start of a bookmark within a WordprocessingML document. This start marker is matched with the appropriately paired end marker by matching the value of the id attribute from the associated bookmarkEnd element.

And how should I produce such an id?

取当前最大的Id并加一个是明智的做法。您可能只能找到一次最大值并从那时起存储它,但与您已经完成的相比,这不会产生巨大差异我不会想到。

integers? to me "Decimal" implies floating-point

ST_DecimalNumber 只允许整数。我认为 decimal 是对以 10 为底的数字的引用,而不是例如十六进制或二进制。

来自第 17.18.10 节(强调我的):

This simple type specifies that its contents contain a whole decimal number (positive or negative), whose contents are interpreted based on the context of the parent XML element.

接着说:

This simple type's contents are a restriction of the W3C XML Schema integer datatype.