문제

XML 문서 "ABC.XML"이 있습니다.

값 노드를 태그 '이름'으로 대체 할 수있는 함수 대체 (name, newValue)를 작성하고 디스크에 다시 작성해야합니다. 파이썬에서 가능합니까? 어떻게해야합니까?

도움이 되었습니까?

해결책

import xml.dom.minidom
filename='abc.xml'
doc = xml.dom.minidom.parse(filename)
print doc.toxml()

c = doc.getElementsByTagName("c")
print c[0].toxml()
c[0].childNodes[0].nodeValue = 'zip'
print doc.toxml()

def replace(tagname, newvalue):
  '''doc is global, first occurrence of tagname gets it!'''
  doc.getElementsByTagName(tagname)[0].childNodes[0].nodeValue = newvalue
replace('c', 'zit')

print doc.toxml()

Minidom을 참조하십시오 뇌관 그리고 API 참조.

# cat abc.xml
<root>
  <a>
    <c>zap</c>
  </a>
  <b>
  </b>
</root>

다른 팁

물론 가능합니다. xml.etree.elementtree 모듈은 XML을 구문 분석, 태그 찾기 및 값을 대체하는 데 도움이됩니다.

변경하려는 XML 파일에 대해 조금 더 알고 있다면 XML 파일을 처리하는 일반적인 기능을 작성 해야하는 경우보다 작업을 좀 더 쉽게 만들 수 있습니다.

Dom Parsing에 이미 익숙한 경우 ElementTree One 대신 사용할 XML.DOM 패키지가 있습니다.

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