【问题标题】:Writing a xml:id attribute with lxml使用 lxml 编写 xml:id 属性
【发布时间】:2017-10-10 18:06:01
【问题描述】:

我正在尝试使用 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 是在之前的某个时间分配的,对我的问题无关紧要。所以我的代码返回给我这一行:

<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/,我知道它在其FAQ 中提到在 lxml 中受支持。

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

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

【问题讨论】:

    标签: python xml lxml w3c


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2015-08-19
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多