如何批量修改XML中符合条件的Game节点Category值?含Notepad++方案
批量修改XML中指定节点的Category值
方法一:用Notepad++实现(完全可行)
Notepad++的正则替换功能可以轻松完成这个需求,步骤如下:
- 打开目标XML文件,按下
Ctrl+H打开替换窗口 - 切换到「正则表达式」模式,勾选「.匹配换行符」选项
- 在「查找目标」框中输入正则表达式:
(<Game>.*?<ApplicationPath>.*hat.*?</ApplicationPath>.*?<Category>)(.*?)(</Category>.*?</Game>)
- 在「替换为」框中输入:
\1puzzle\3
- 点击「全部替换」即可完成批量修改
说明:该正则会精准匹配包含含"hat"的ApplicationPath的整个Game节点,定位到对应的Category标签后,将原有值替换为"puzzle"。
方法二:Python脚本(适合复杂XML结构)
如果XML存在嵌套或格式不规整的情况,用Python处理更稳妥,代码示例:
import xml.etree.ElementTree as ET # 加载目标XML文件 tree = ET.parse('your_game_file.xml') root = tree.getroot() # 遍历所有Game节点 for game in root.findall('Game'): app_path_elem = game.find('ApplicationPath') if app_path_elem is not None and app_path_elem.text and 'hat' in app_path_elem.text: # 修改对应Category的值 category_elem = game.find('Category') if category_elem is not None: category_elem.text = 'puzzle' # 保存修改后的XML文件 tree.write('modified_game_file.xml', encoding='utf-8', xml_declaration=True)
将代码中的your_game_file.xml替换为你的XML文件名,运行脚本即可生成修改后的文件。
内容的提问来源于stack exchange,提问作者Sweepster
相关产品推荐
相关产品推荐

