PythonはXMLを解析します。

PythonはXMLを解析します。

XMLファイルから特定のタグを削除する必要があります。以下のサンプルXML。

       <data>
          <tag:action/>
        </data>

dataと/ dataの間のすべての内容を削除したいと思います。公開後、XMLタグは質問に表示されません。

Python ElementTree xmlパーサーのRemove()メソッドを使用してこれを行うことができます。要素を削除したら、変更した内容を新しいコンテンツに書き込みます。

tree.write('new.xml');

問題は、元のxmlファイルのすべてのタグ名が等に変更されることですns0ns1new.xml

他のすべての内容を変更せずにXMLファイルを変更する方法はありますか?

ベストアンサー1

きれいなスープを使って仕事をすることができます。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import bs4

content = '''
<people>

  <person born="1975">
    <name>
      <first_name>John</first_name>
      <last_name>Doe</last_name>
    </name>
    <profession>computer scientist</profession>
    <homepage href="http://www.example.com/johndoe"/>
  </person>

  <person born="1977">
    <name>
      <first_name>Jane</first_name>
      <last_name>Doe</last_name>
    </name>
    <profession>computer scientist</profession>
    <homepage href="http://www.example.com/janedoe"/>
  </person>

</people>
'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(content)

for s in soup('name'):
    s.extract()

print(soup)

次の結果が生成されます。

<html><body><people>
<person born="1975">

<profession>computer scientist</profession>
<homepage href="http://www.example.com/johndoe"></homepage>
</person>
<person born="1977">

<profession>computer scientist</profession>
<homepage href="http://www.example.com/janedoe"></homepage>
</person>
</people>
</body></html>

名前空間の使用:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import bs4

content = '''<people xmlns:h="http://www.example.com/to/">

  <h:person born="1975">
    <h:name>
      <h:first_name>John</h:first_name>
      <h:last_name>Doe</h:last_name>
    </h:name>
    <h:profession>computer scientist</h:profession>
    <h:homepage href="http://www.example.com/johndoe"/>
  </h:person>

  <h:person born="1977">
    <h:name>
      <h:first_name>Jane</h:first_name>
      <h:last_name>Doe</h:last_name>
    </h:name>
    <h:profession>computer scientist</h:profession>
    <h:homepage href="http://www.example.com/janedoe"/>
  </h:person>

</people>
'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(content).people

for s in soup('h:name'):
    s.extract()

print(soup)

結果に.peopleブロックを追加しました。<html><body> </body></html>

<people xmlns:h="http://www.example.com/to/">
<h:person born="1975">

<h:profession>computer scientist</h:profession>
<h:homepage href="http://www.example.com/johndoe"></h:homepage>
</h:person>
<h:person born="1977">

<h:profession>computer scientist</h:profession>
<h:homepage href="http://www.example.com/janedoe"></h:homepage>
</h:person>
</people>

おすすめ記事