用lxml替换xml元素

时间:2017-01-19 13:02:09

标签: python lxml

我有这个复杂的xml文件,我们需要动态更新其中的一些元素。我已经成功地使用lxml更新了值字符串(属性),但我完全不确定如何更换整个元素。这里有一些伪代码来展示我正在尝试做的事情。     进口口     来自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”var中的值。

我很难在网上浏览lxml信息,但我似乎找不到类似于我想要做的例子。

任何指示赞赏!

1 个答案:

答案 0 :(得分:0)

您应该只删除节点上的索引访问权限:

value [0] .getparent()。replace(value [0],新树)

....至: value.getparent()。replace(value,newtree)