-2

入力xmlを受け取り、同じxmlを出力として出力するプログラムがあります。そのためのクラスとメソッドをどのように実装できますか?

import xml.etree.ElementTree as ET
import sys   
doc       = ET.parse("users.xml")
root      = doc.getroot()
root_new  = ET.Element("users") 
for child in root:
    username             = child.attrib['username']
    password             = child.attrib['password']   
    # create "user" here
    user    = ET.SubElement(root_new, "user") 
    user.set("username",username)               
    user.set("password",password) 
    #checking attribute for skipping KeyError
    if 'remote_access' in child.attrib:
        remote_access   = child.attrib['remote_access']
        user.set("remote_access",remote_access) 
    for g in child.findall("group"):
        # create "group" here
        group     = ET.SubElement(user,"group")  
        if g.text != "lion":
            group.text = g.text 
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)

これをクラスの概念に変換する方法。前もって感謝します。

4

1 に答える 1

2

私があなたを正しく理解していれば、おそらく何千もの方法があります。あなたは例が欲しいです、ここにあります(私はあなたのコードが機能していると仮定しています):

import xml.etree.ElementTree as ET
import sys   


class MyXmlParser(object):

    def __init__(self, xml_file_name):
        self.doc  = ET.parse(xml_file_name)
        self.root = doc.getroot()

    def do_something(self, output = sys.stdout):
        root_new  = ET.Element("users") 
        for child in self.root:
            username             = child.attrib['username']
            password             = child.attrib['password']   
            # create "user" here
            user    = ET.SubElement(root_new, "user") 
            user.set("username",username)               
            user.set("password",password) 
            # checking attribute - skip KeyError
            try:
                remote_access   = child.attrib['remote_access']
                user.set("remote_access", remote_access) 
            except KeyError:
                pass

            for g in child.findall("group"):
                # create "group" here
                group     = ET.SubElement(user,"group")  
                if g.text != "lion":
                    group.text = g.text 
        tree = ET.ElementTree(root_new)
        tree.write(output)

def main():
    my_parser = MyXmlParser("users.xml")
    my_parser.do_something()

if __name__ == '__main__':
    main()
于 2012-11-06T11:58:59.953 に答える