【问题标题】:Using python to replace a single element in multiple xml files with the same element from a different set使用python用不同集合中的相同元素替换多个xml文件中的单个元素
【发布时间】:2021-03-26 14:54:01
【问题描述】:

我有两个单独的 xml 文件夹;一个文件夹包含相同记录的旧版本,一个包含更新版本。我需要用旧的替换新集合中每条记录中的一个元素。皱纹:文件名不匹配,需要保留较新集的文件名。也就是说,每条记录都有一个唯一的值,可以用作匹配文件的关键字段。

需要替换的元素集是<mods:name>。示例:以下 -

      <mods:name>
         <mods:namePart>Example creator</mods:namePart>
         <mods:role>
            <mods:roleTerm type="text">creator</mods:roleTerm>
         </mods:role>
      </mods:name>

需要替换为-

      <mods:name>
         <mods:namePart>Example creator</mods:namePart>
         <mods:role>
            <mods:roleTerm type="text">creator</mods:roleTerm>
         </mods:role>
         <mods:namePart>Example owner</mods:namePart>
         <mods:role>
            <mods:roleTerm type="text">owner</mods:roleTerm>
         </mods:role>
      </mods:name>

可以用作键的字段是&lt;mods:identifier&gt;(出现在完整文件中,但未在这些sn-ps中显示)。示例 -

&lt;mods:identifier type="local"&gt;dc_031_001&lt;/mods:identifier&gt;

我想要某种 python 解决方案,但我愿意接受建议。非常感谢您的阅读。

【问题讨论】:

  • 原始或替换 xml 中都没有 &lt;mods:identifier&gt;
  • 杰克,&lt;mods:identifier&gt; 出现在完整文件中。我只在这里发布了sn-ps。

标签: python xml merge


【解决方案1】:
import etree as ET

root = ET.getroot('old_doc')

replacement_dict = {}

identifiers = root.findall('.//mods:identifier')

for identifier in identifiers:
   #this part is a little wishy washy because I can't see the relationship between identifier element and the elements you want
   try:   
      identifier_text = identifier.text
      replacement_elem = #use a .find or a getnext or whatever depending on the relationship
      replacement_elem_text = replacement_elem.text    
      temp_dict = {identifier_text: replacement_elem_text}

root2 = ET.getroot('new_doc')

new_identifiers = root2.findall('mods:identifier')

for new_identifier in new_identifiers:
   #get both elements as before
   if new_identifier.text in replacement_dict:
      elem_to_be_replaced.text = replacement_dict.get(new_identifier_text)

其中一些是伪代码,但它应该能让你到达你需要去的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2016-02-14
    • 2021-11-27
    • 1970-01-01
    相关资源
    最近更新 更多