0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BeautifulSoupを使ったxml編集あれこれ

Posted at

はじめに

BeautifulSoupでxmlの要素取得についてはググればいくらでも出てくるが、それを使ってxmlの編集なんかはあまり出てこず。。
今回、2つのxmlを使って要素の挿入を行ったので備忘録として残しておきます。
(今後他にも編集が必要になれば都度更新していきます)

やりたいこと

以下の2つのxmlを使う。sample2.xmlのfoodタグを、sample1.xmlのfoodタグとgroupタグの間に挿入する

sample1.xml
<?xml version="1.0" encoding="UTF-8" ?>
<foods>
  <food id="123">
    <name>バナナ</name>
    <color>黄色</color>
  </food>

  <group>
    <name>果物</name>
    <color>なし</color>
  </group>
</foods>
sample2.xml
<?xml version="1.0" encoding="UTF-8" ?>
<foods>
  <food id="456">
    <name>ぶどう</name>
    <color>紫色</color>
  </food>

  <group>
    <name>果物</name>
    <color>なし</color>
  </group>
</foods>

やったこと

簡単にできた

test.py
from bs4 import BeautifulSoup

# ファイルの読み込み
f1 = open('sample1.xml','r')
soup1 = BeautifulSoup(f1, 'html.parser')
f1.close()

f2 = open('sample2.xml','r')
soup2 = BeautifulSoup(f2, 'html.parser')
f2.close()

# sample2.xmlから<food>タグを取得
new_tag = soup2.food

# sample1の<group>タグの上に挿入
soup1.group.insert_before(new_tag)

アウトプット

output.xml
<?xml version="1.0" encoding="UTF-8" ?>
<foods>
 <food id="123">
  <name>バナナ</name>
  <color>黄色</color>
 </food>
 <food id="456">
  <name>ぶどう</name>
  <color>紫色</color>
 </food>
 <group>
  <name>果物</name>
  <color>なし</color>
 </group>
</foods>
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?