简体   繁体   English

如何用漂亮的汤/ python重建xml密钥?

[英]How to rebuild an xml key with beautiful soup/python?

So, using beautiful soup, I am trying to parse through a large xml file and strip out the first string (before .) from each key name. 因此,我尝试使用漂亮的汤来解析一个大的xml文件,并从每个键名中删除第一个字符串(。之前)。

Just as an example: 举个例子:

currently print key gives me: 当前的打印键给我:

<key name="app-suite.multi.port" value="15022"></key>

and print key["name"].split(".")[1:] gives me: print key["name"].split(".")[1:]给我:

['multicast', 'port']

Stripping out app-suite out of the keyname is the desired result, however I'm not sure how to rebuild this key. 从键名中剥离应用套件是理想的结果,但是我不确定如何重建此键。 Currently the above line just returns a list with the correct elements. 当前,上面的行仅返回包含正确元素的列表。

How do I actually turn this into a key or modify the original key by removing 'app-suite'? 我实际上如何将其变成密钥或通过删除“应用套件”来修改原始密钥?

Assuming you actually want to keep the . 假设您实际上想要保留该. in multi.port , it is better to use split(., 1) so that you only split on the first instance of . multi.port ,最好使用split(., 1)以便仅在的第一个实例上进行拆分. . You can use the following: 您可以使用以下内容:

from bs4 import BeautifulSoup

content = '<key name="app-suite.multi.port" value="15022"></key>'
soup = BeautifulSoup(content)
key = soup.find('key')
key['name'] = key["name"].split(".", 1)[1]
print(key)

Output 产量

<key name="multi.port" value="15022"></key>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM