用 lxml 写一个 xml:id 属性

Writing a xml:id attribute with lxml

我正在尝试用 lxml 重建 TEI-XML 文件。

我的文件开头是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="https://www.ssrq-sds-fds.ch/tei/TEI_Schema_SSRQ.rng" 
            type="application/xml" 
            schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model href="https://www.ssrq-sds-fds.ch/tei/TEI_Schema_SSRQ.rng" 
            type="application/xml" 
            schematypens="http://purl.oclc.org/dsdl/schematron"?>
<?xml-stylesheet type="text/css" 
                 href="https://www.ssrq-sds-fds.ch/tei/Textkritik_Version_tei-ssrq.css"?>

<TEI xmlns:xi="http://www.w3.org/2001/XInclude" 
     xmlns="http://www.tei-c.org/ns/1.0" n="" 
     xml:id="[To be generated]" <!-- e.g. StAAG_U-17_0007a --> >

前四行在我看来应该无关紧要,但为了完整起见我将它们包括在内。我的问题始于 TEI-Element。 所以我复制它的代码如下所示:

NSMAP = {"xml":"http://www.tei-c.org/ns/1.0",
         "xi":"http://www.w3.org/2001/XInclude"}
root = et.Element('TEI', n="", nsmap=NSMAP)
root.attrib["id"] = xml_id
root.attrib["xmlns"] = "http://www.tei-c.org/ns/1.0"

字符串 xml_id 是在之前的某个时间分配的,与我的问题无关。所以我的代码 returns 我这一行:

<TEI xmlns:xi="http://www.w3.org/2001/XInclude"
     n=""
     id="StAAG_U-17_0006"
     xmlns="http://www.tei-c.org/ns/1.0">

所以唯一缺少的就是这个 xml:id 属性。我找到了这个规范页面:https://www.w3.org/TR/xml-id/ and I know it is mentioned to be supported in lxml in its FAQ.

顺便说一句,root.attrib["xml:id"] 不起作用,因为它不是一个可行的属性名称。

所以,有谁知道如何将我的 ID 分配给元素的 xml:id 属性?

您需要指定 id 是默认 xml 命名空间的一部分。试试这个:

root.attrib["{http://www.w3.org/XML/1998/namespace}id"] = xml_id

参考:https://www.w3.org/TR/xml-names/#ns-decl