【问题标题】:How do I insert a tag that holds the text of an older tag in xml using python?如何使用 python 在 xml 中插入一个包含旧标签文本的标签?
【发布时间】:2021-06-12 19:24:54
【问题描述】:

我想在已经存在的标签内插入 s 标签,并将旧标签的文本移动到 s 标签内。例如,如果我的 XML 文件如下所示:

<root>
    <name>Light and dark</name>
    <address>
        <sector>142</sector>
        <location>Noida</location>
    </address>
</root>

我希望它是这样的(检查名称标签):

<root>
    <name>
        <s>Light and dark</s>
    </name>
    <address>
        <sector>142</sector>
        <location>Noida</location>
    </address>
</root>

我尝试使用 ET.SubElement,但结果不一样。

【问题讨论】:

  • 使用 XSLT 来完成这些任务要好得多。如果你愿意这样做,我可以告诉你如何做。
  • 当然,我不介意使用 XSLT。请做。

标签: python xml xml.etree


【解决方案1】:

将 XSLT 用于此类任务要好得多。

XSLT 有所谓的 Identity Transform 模式。

输入 XML

<root>
    <name>Light and dark</name>
    <address>
        <sector>142</sector>
        <location>Noida</location>
    </address>
</root>

XSLT

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="name">
        <xsl:copy>
            <s>
                <xsl:value-of select="."/>
            </s>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

输出 XML

<root>
  <name>
    <s>Light and dark</s>
  </name>
  <address>
    <sector>142</sector>
    <location>Noida</location>
  </address>
</root>

【讨论】:

    【解决方案2】:

    要使用 ElementTree XML API 在 XML 中插入子元素,请附加新元素,然后将其设置为父元素的文本值。

    import xml.etree.ElementTree as ET
    
    xml = """
     <root>
        <name>Light and dark</name>
        <address>
           <sector>142</sector>
           <location>Noida</location>
        </address>
     </root>"""
    
    root = ET.fromstring(xml)
    
    # 1. find name element in document
    name = root.find('name')
    
    # 2. get text value and reset the element
    text = name.text
    name.clear()
    
    # 3. create new element s and set text
    elt = ET.SubElement(name, "s")
    elt.text = text
    
    print(ET.tostring(root, encoding='unicode'))
    

    要处理多个元素,请在步骤 1-3 周围添加一个循环:

    for child in root.findall('name'):
        text = child.text
        child.clear()
        elt = ET.SubElement(child, "s")
        elt.text = text
    

    输出:

    <root>
       <name><s>Light and dark</s></name>
       <address>
        <sector>142</sector>
        <location>Noida</location>
       </address>
     </root>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多