質問

ようにしていをカスタマイズxmlファイルからテンプレートxmlファイルエラーになります。

概念的には、読みたい、xmlテンプレートの削除、一部の要素が一部変更にテキスト属性、および書のxmlにファイルです。して欲しいという事で作品のようなこと:

conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']

conf_new = ConvertDictToXml(conf_base_dict)

いいたい書き込むファイルもしっかり身につけるた方へ ElementTree.ElementTree.write()

conf_new.write('config-new.xml') 

る方法はありませるのですが誰かこうに異なる。

役に立ちましたか?

解決

簡単に操作できるXMLのpythonでは、私のように 美しいスープ 図書館があります。この作品のようなこと:

サンプルXMLファイル:

<root>
  <level1>leaf1</level1>
  <level2>leaf2</level2>
</root>

Pythonコード:

from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString

soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file
soup.contents[0].name
# u'root'

利用できるノード名と方法:

soup.root.contents[0].name
# u'level1'

ることも可能で利用regexes:

import re
tags_starting_with_level = soup.findAll(re.compile('^level'))
for tag in tags_starting_with_level: print tag.name
# level1
# level2

の追加及び挿入す新しいノードは非常に簡単で:

# build and insert a new level with a new leaf
level3 = Tag(soup, 'level3')
level3.insert(0, NavigableString('leaf3')
soup.root.insert(2, level3)

print soup.prettify()
# <root>
#  <level1>
#   leaf1
#  </level1>
#  <level2>
#   leaf2
#  </level2>
#  <level3>
#   leaf3
#  </level3>
# </root>

他のヒント

こういdictマイナス属性...ソ連邦の場合に有用であります。私は使用しませんでしたが、xmlを辞液自分がいた。



import xml.etree.ElementTree as etree

tree = etree.parse('test.xml')
root = tree.getroot()

def xml_to_dict(el):
  d={}
  if el.text:
    d[el.tag] = el.text
  else:
    d[el.tag] = {}
  children = el.getchildren()
  if children:
    d[el.tag] = map(xml_to_dict, children)
  return d

この: http://www.w3schools.com/XML/note.xml

<note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend!</body>
</note>

が等しいこ


{'note': [{'to': 'Tove'},
          {'from': 'Jani'},
          {'heading': 'Reminder'},
          {'body': "Don't forget me this weekend!"}]}

くなった場合に変換し情報セットを入れ子dicts初が容易といった利点があります。使用ElementTree、これを実行する事ができます。:

import xml.etree.ElementTree as ET
doc = ET.parse("template.xml")
lvl1 = doc.findall("level1-name")[0]
lvl1.remove(lvl1.find("leaf1")
lvl1.remove(lvl1.find("leaf2")
# or use del lvl1[idx]
doc.write("config-new.xml")

ElementTreeよう配慮されてい換されたXMLのために樹木のリストおよび属性が最初で使うことになります。

でもサポートとして小型のサブセット XPath.

私の修飾のダニエルの答えは、小幅のneater辞書

def xml_to_dictionary(element):
    l = len(namespace)
    dictionary={}
    tag = element.tag[l:]
    if element.text:
        if (element.text == ' '):
            dictionary[tag] = {}
        else:
            dictionary[tag] = element.text
    children = element.getchildren()
    if children:
        subdictionary = {}
        for child in children:
            for k,v in xml_to_dictionary(child).items():
                if k in subdictionary:
                    if ( isinstance(subdictionary[k], list)):
                        subdictionary[k].append(v)
                    else:
                        subdictionary[k] = [subdictionary[k], v]
                else:
                    subdictionary[k] = v
        if (dictionary[tag] == {}):
            dictionary[tag] = subdictionary
        else:
            dictionary[tag] = [dictionary[tag], subdictionary]
    if element.attrib:
        attribs = {}
        for k,v in element.attrib.items():
            attribs[k] = v
        if (dictionary[tag] == {}):
            dictionary[tag] = attribs
        else:
            dictionary[tag] = [dictionary[tag], attribs]
    return dictionary

名前空間はxmlns文字列を含むブレース、ElementTree prependsすべてのタグは、こちらかをクリアしてある名前空間のドキュメント全体

NBその調整のと、raw xmlのも、その"空"タグを製造する最大a''テキストの特性にElementTree表現

spacepattern = re.compile(r'\s+')
mydictionary = xml_to_dictionary(ElementTree.XML(spacepattern.sub(' ', content)))

うためのインスタンス

{'note': {'to': 'Tove',
         'from': 'Jani',
         'heading': 'Reminder',
         'body': "Don't forget me this weekend!"}}

この設計のための特定のxmlることは基本的には相当のjsonに処理する必要がありますの要素の属性等

<elementName attributeName='attributeContent'>elementContent</elementName>

すぎ

あの可能性の融合、属性の辞書/subtag辞書同様にどのように繰り返しsubtags合併した場合は、入れ子のリストのような適切:-)

を追加することにより線

d.update(('@' + k, v) for k, v in el.attrib.iteritems())

user247686コード できるノードの属性です。

かこ https://stackoverflow.com/a/7684581/1395962

例:

import xml.etree.ElementTree as etree
from urllib import urlopen

xml_file = "http://your_xml_url"
tree = etree.parse(urlopen(xml_file))
root = tree.getroot()

def xml_to_dict(el):
    d={}
    if el.text:
        d[el.tag] = el.text
    else:
        d[el.tag] = {}
    children = el.getchildren()
    if children:
        d[el.tag] = map(xml_to_dict, children)

    d.update(('@' + k, v) for k, v in el.attrib.iteritems())

    return d

電話として

xml_to_dict(root)

してください。

print xml.etree.ElementTree.tostring( conf_new )

アルファベットをクリックにした

root        = ET.parse(xh)
data        = root.getroot()
xdic        = {}
if data > None:
    for part in data.getchildren():
        xdic[part.tag] = part.text

XMLには豊かinfoset、特別な表示にするにはPythonの辞書です。要素は、属性としている要素体等

プロジェクトを取り扱間で往XMLおよびPythonの辞書は、一部の設定のオプションのトレードオフの異なる方法であ XML支援ツールの酸洗.バージョン1.3以上が必要です。ではない純粋なPython(現実であるとして、C++/Pythonの相互作用ではなく、それが適切な利用例です。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top