【问题标题】:How to modify the content of an XML node using python?如何使用 python 修改 XML 节点的内容?
【发布时间】:2019-02-17 10:05:20
【问题描述】:

我有一个简单的问题,我想使用 python 更新/修改 xml 节点的内容。我使用的是 python 3.6 版本。

我想编写一个 python 脚本,将状态节点内容修改为“On”,将 directoryName 节点修改为“Users/”

 <main>
        <status>off</status>

        <directoryName>nothing</directoryName>

 </main>

【问题讨论】:

标签: python xml python-3.x


【解决方案1】:

我得到了答案。最后忘记写了

 xmlHandler = "System_Settings/System_controller.xml"

    xmlDom=ElementTree.parse(xmlHandler)

    xmlDom.find("status").text = "on"
    print(xmlDom.find("status").text)

    xmlDom.write(xmlHandler)

【讨论】:

    【解决方案2】:

    如果您有能力安装额外的软件包,请查看BeautifulSoup。它使解析 html 和 xml 变得非常简单。

    import bs4
    xml = """
    <main>
        <status>off</status>
        <directoryName>nothing</directoryName>
    </main>"""
    soup = bs4.BeautifulSoup(xml, "xml")
    soup.status.string="on"
    print(soup.prettify())
    

    【讨论】:

      【解决方案3】:

      使用lxml 库(BeautifulSoup 也使用该库):

      from lxml import etree
      
      node = etree.XML("""
      <main>
          <status>off</status>
          <directoryName>nothing</directoryName>
      </main>""")
      status = "On"
      
      status_node = node.xpath("/main/status")[0]
      status_node.text = status
      

      然后使用print(etree.tounicode(node)),你会得到:

      <main>
          <status>On</status>
          <directoryName>nothing</directoryName>
      </main>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多