用lxml替换xml元素。

问题描述 投票:0回答:1

我有一个复杂的xml文件,我们需要动态更新其中的一些元素。我已经成功地使用lxml更新了值字符串(属性),但我完全不知道如何去替换整个元素。下面是一些伪代码来展示我想做的事情。 import os from lxml import etree

directory_name = "C:\\apps"
file_name = "web.config"

xpath_identifier = '/configuration/applicationSettings/Things/setting[@name="CorsTrustedOrigins"]'

#contents of the xml file for reference:
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Things" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    </sectionGroup>
  </configSections>
  <appSettings/>   
  <applicationSettings>
    <Things>
      <setting name="CorsTrustedOrigins" serializeAs="Xml">
        <value>
          <ArrayOfString>
           <string>http://localhost:51363</string>
           <string>http://localhost:3333</string>
          </ArrayOfString>
        </value>
      </setting>
    </Things>
  </applicationSettings>
</configuration>

file_full_path = os.path.join(directory_name, file_name)
tree = etree.parse(file_full_path)
root = tree.getroot()

etree.tostring(root)


xpath_identifier = str(xpath_identifier)

value = root.xpath(xpath_identifier)

#This successfully prints the element I'm after, so I'm sure my xpath is good:
etree.tostring(value[0])

#This is the new xml element I want to replace the current xpath'ed element with:
newxml = '''
<setting name="CorsTrustedOrigins" serializeAs="Xml">
        <value>
          <ArrayOfString>
            <string>http://maddafakka</string>
          </ArrayOfString>
        </value>
      </setting>
'''

newtree = etree.fromstring(newxml)

#I've tried this:
value[0].getparent().replace(value[0], newtree)

#and this
value[0] = newtree

#The value of value[0] gets updated, but the "root document" does not.

我想做的是更新 "ArrayofStrings "元素,以反映 "newxml "变量中的值。

我正在努力浏览网上的lxml信息,但我似乎找不到与我试图做的类似的例子。

感谢任何提示

python lxml
1个回答
0
投票

你应该直接删除节点上的索引访问。

value[0].getparent().replace(value[0], newtree)

...... to:value.getparent().replace(value, newtree)

© www.soinside.com 2019 - 2024. All rights reserved.