PythonでのXML解析?
Python XMLパーサーパーサーは、XMLファイルから有用な情報を読み取って抽出する最も簡単な方法の1つを提供します。この短いチュートリアルでは、Python ElementTree XML APIを使用してXMLファイルを解析し、XMLドキュメントを変更および作成する方法を説明します。
Python ElementTree APIは、XMLデータを抽出、解析、変換する最も簡単な方法の1つです。
それでは、ElementTreeを使用してPythonXMLパーサーの使用を開始しましょう。
例1
XMLファイルの作成
まず、要素とサブ要素を含む新しいXMLファイルを作成します。
#Import required library
import xml.etree.ElementTree as xml
def createXML(filename):
# Start with the root element
root = xml.Element("users")
children1 = xml.Element("user")
root.append(children1)
tree = xml.ElementTree(root)
with open(filename, "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
createXML("testXML.xml") 上記のプログラムを実行すると、現在のデフォルトの作業ディレクトリに「textXML.xml」という名前の新しいファイルが作成されます。
次のようなコンテンツが含まれています:
<users><user /></users>
ファイルの書き込み中は、「wb」モードを使用していることに注意してください。バイナリモードでファイルを書き込みます。
XML要素への値の追加
上記のプログラムのXML要素にいくつかの値を与えましょう:
#Import required library
import xml.etree.ElementTree as xml
def createXML(filename):
# Start with the root element
root = xml.Element("users")
children1 = xml.Element("user")
root.append(children1)
userId1 = xml.SubElement(children1, "Id")
userId1.text = "hello"
userName1 = xml.SubElement(children1, "Name")
userName1.text = "Rajesh"
tree = xml.ElementTree(root)
with open(filename, "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
createXML("testXML.xml") 上記のプログラムを実行すると、次のような値が新しい要素に追加されることがわかります。
<users> <user> <Id>hello</Id> <Name>Rajesh</Name> </user> </users>
上記の出力は問題ないようです。
それでは、ファイルの編集を始めましょう:
XMLデータの編集
既存のプログラムのファイルからデータを少し追加しましょう。
newdata.xml
<users> <user> <id>1a</id> <name>Rajesh</name> <salary>NA</salary> </user> <user> <id>2b</id> <name>TutorialsPoint</name> <salary>NA</salary> </user> <user> <id>3c</id> <name>Others</name> <salary>NA</salary> </user> </users>
上記は現在のxmlファイルです。各ユーザーの給与を更新してみましょう:
#Import required library
import xml.etree.ElementTree as ET
def updateET(filename):
# Start with the root element
tree = ET.ElementTree(file=filename)
root = tree.getroot()
for salary in root.iter('salary'):
salary.text = '500000'
tree = ET.ElementTree(root)
with open("newdata.xml", "wb") as fh:
tree.write(fh)
if __name__ == "__main__":
updateET("newdata.xml") 出力
したがって、給与が「NA」から「500000」に変更されていることがわかります。
例:PythonXMLパーサー
次に、ファイルに存在するXMLデータを解析してデータを出力する別のプログラムを作成しましょう。
#Import required library
import xml.etree.cElementTree as ET
def parseXML(file_name):
# Parse XML with ElementTree
tree = ET.ElementTree(file=file_name)
print(tree.getroot())
root = tree.getroot()
print("tag=%s, attrib=%s" % (root.tag, root.attrib))
# get the information via the children!
print("-" * 25)
print("Iterating using getchildren()")
print("-" * 25)
users = root.getchildren()
for user in users:
user_children = user.getchildren()
for user_child in user_children:
print("%s=%s" % (user_child.tag, user_child.text))
if __name__ == "__main__":
parseXML("newdata.xml") 出力
<Element 'users' at 0x0551A5A0>
tag = users, attrib = {}
-------------------------
Iterating using getchildren()
-------------------------
id = 1a
name = Rajesh
salary = 500000
id = 2b
name = TutorialsPoint
salary = 500000
id = 3c
name = Others
salary = 500000 -
Pythonのissuperset()
この記事では、Pythonでのissuperset()と、さまざまな分野でのその実装について学習します。 このメソッドは、セットBのすべての要素に引数として渡されるすべての要素セットAが含まれている場合はブール値Trueを返し、Aのすべての要素がBに存在しない場合はfalseを返します。 これは、BがAのスーパーセットである場合、それを意味します returns true; else False 例 いくつかの例を見てみましょう A = {'t','u','t','o','r','i',
-
Pythonを使用してXMLを生成する方法は?
PythonディクショナリからXMLを生成するには、dicttoxmlパッケージをインストールする必要があります。 −を使用してインストールできます $ pip install dicttoxml インストールすると、dicttoxmlメソッドを使用してxmlを作成できます。 例 a = { 'foo': 45, 'bar': { 'baz': "Hello" } } xml = dicttoxml.dic