문제

파이썬에서 템플릿 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을 쉽게 조작하기 위해 나는 아름다운 수프 도서관. 다음과 같이 작동합니다.

샘플 XML 파일 :

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

파이썬 코드 :

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 마이너스 속성을 얻을 수 있습니다 ... 이것이 다른 사람에게 유용하다면 Dunno. 나는 이것을 생각해 냈을 때 솔루션을 직접 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!"}]}

정보 세트를 중첩 된 딕트로 먼저 변환하는 것이 더 쉬운 지 잘 모르겠습니다. 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.

다니엘의 대답에 대한 나의 수정, 약간 깔끔한 사전을 제공하기 위해 :

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 문자열입니다.

NB는 원시 XML을 조정하여 '빈'태그가 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!"}}

기본적으로 JSON과 동등한 특정 XML 용으로 설계되었으며 다음과 같은 요소 속성을 처리해야합니다.

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

~도

목록을 둥지로 보이지만 반복 서브 탭이 병합되는 방식과 유사하게 속성 사전 / 서브 탭 사전을 병합 할 가능성이 있습니다.

이 줄을 추가합니다

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에는 리치 인포셋이 있으며 파이썬 사전에서이를 나타내는 데 특별한 트릭이 필요합니다. 요소가 주문되고 속성은 요소 본체 등과 구별됩니다.

XML과 Python Dictionaries 간의 왕복을 처리하기위한 하나의 프로젝트는 다른 방식으로 트레이드 오프를 처리하기위한 일부 구성 옵션이 있습니다. 산세 도구에서 XML 지원. 버전 1.3 및 최신이 필요합니다. 순수한 파이썬은 아니지만 실제로 C ++ / Python 상호 작용을 더 쉽게 만들 수 있도록 설계되었지만 다양한 사용 사례에 적합 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top