2017-04-03 8 views
1

私は、dictをXMLに変換するために、Pythonでdicttoxmlを使用しています。属性付きXMLへの変換

dictをXML属性に変換する必要があります。例えば

辞書

[ 
     { 
      "@name":"Ravi", 
      "@age":21, 
      "college":"Anna University" 
     } 
] 

出力XML

<Student name="Ravi" age=21> 
    <college>Anna University</college> 
</Student> 

コード

dicttoxml(dict, custom_root='Student', attr_type=False, root=True) 

実際の出力

<Student> 
    <key name="name">Ravi</key> 
    <key name="age">21</key> 
    <college>Anna University</college> 
</Student> 

答えて

1

私はdeclxml(完全な情報開示:私はそれを書いた)を提案するかもしれません。 declxmlを使用して、プロセッサーというオブジェクトを作成し、XMLの構造を宣言的に定義します。このプロセッサを使用して、XMLデータの解析とシリアライズを行うことができます。 declxmlは、辞書、オブジェクト、および名前付きタプルとのシリアル化を行います。これは、要素の属性と配列を処理し、基本的な検証を実行します。所望の出力を生成

import declxml as xml 


student = { 
    'name':'Ravi', 
    'age':21, 
    'college':'Anna University' 
} 

student_processor = xml.dictionary('Student', [ 
    xml.string('.', attribute='name'), 
    xml.integer('.', attribute='age'), 
    xml.string('college') 
]) 

xml.serialize_to_string(student_processor, student, indent=' ') 

<?xml version="1.0" ?> 
<Student age="21" name="Ravi"> 
    <college>Anna University</college> 
</Student> 
関連する問題