python修改xml文件_python删除xml文件的指定标签

博客介绍了使用Python修改大体积XML文件的方法。通过读取delete.txt文件获取需删除的re标签的id,再利用BeautifulSoup套件解析XML文件,定义过滤函数找出对应标签并删除,最后输出修改后的文件。

有个xml文件的格式大致如下:

123

abc

126

abc

135

abc

147

abc

然后另外一个delete.txt保存的是需要删除的re标签的id。假设txt内容如下:

126

147

需要做的就是读取这个delete.txt文件,然后在xml中找到这些id对应的标签将其全部删除,如上例的结果就是:

123

abc

135

abc

请问是怎么做的。。另外需要提到的是这个xml文件挺大的,有200多M。

你可以使用

1BeautifulSoup

套件:

安裝:

1pip install bs4

如果覺得

1html

解析器不敷使用,參考文檔安裝其他適合的解析器。

如果想要詳細了解

1BeautifulSoup

也請參考官方文檔(有中文版本)。

測試檔:

以下是我使用的測試文件:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22# delete.txt

126

147

# test.xml

<re>

<id>123</id>

<name>abc</name>

</re>

<re>

<id>126</id>

<name>abc</name>

</re>

<re>

<id>135</id>

<name>abc</name>

</re>

<re>

<id>147</id>

<name>abc</name>

</re>

代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22from bs4 import BeautifulSoup

with open('test.xml') as reader:

xml = reader.read()

deleted_id = []

with open('delete.txt') as reader:

for line in reader:

line = line.strip()

deleted_id.append(line)

def has_delete_id(tag):

return tag.name=='re' and tag.id.string in deleted_id

soup = BeautifulSoup(xml, 'html.parser')

tags = soup(has_delete_id)

for tag in tags:

tag.decompose()

print(soup.prettify())

程式輸出:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16<re>

<id>

123

</id>

<name>

abc

</name>

</re>

<re>

<id>

135

</id>

<name>

abc

</name>

</re>

代碼說明:

首先我們從

1Beautiful Soup

的套件中匯入

1BeautifulSoup

1from bs4 import BeautifulSoup

接著分別從

1delete.txt

1test.xml

中讀出要刪除的 id 和主要的 xml 內容,下一步是實體化生成一個

1BeautifulSoup

對象

1soup

, 我們採用

1html.parser

解析器去解析

1xml

:

1soup = BeautifulSoup(xml, 'html.parser')

在此我們定義了一個用於過濾的 function

1has_delete_id

,每一個在

1xml

中的tag 只要是

1<re>

tag 且含有想要刪除的

1<id>

tag 就會被檢索出來:

1

2def has_delete_id(tag):

return tag.name=='re' and tag.id.string in deleted_id

接著

1soup(has_delete_id)

會幫助我們找到欲刪除的 tag,接著走訪搜索出來的這些 tag 並呼叫方法

1decompose()

來從文件中刪除該標籤。

最後

1soup.prettify()

可以幫助我們輸出修改後的文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值