Python xml 분석 기록

1600 단어 Python
Python 의 xml 분석 방식 은 3 가지 가 있 습 니 다. xml. dom. *, xml. sax. * 와 xml. etree. Element Tree 는 상대 적 으로 xml. etree. Element Tree 가 가장 빠 르 고 편리 합 니 다.
xml. etree. ElementTree 만 사 용 했 기 때문에 xml. etree. ElementTree 와 관련 된 것 을 간단하게 기록 합 니 다.
기본 읽 기와 쓰기
참고:http://blog.csdn.net/wklken/article/details/7603071
xmlTree = ElementTree.parse('a.xml')  #  
	xmlNodeList = xmlTree.getiterator('Item')  #      
	for node in xmlNodeList:
		print 'node.tag:%s' % node.tag  #   
		print 'node.text:%s' % node.text  #    
		if node.attrib.has_key('attr_name'):  #  attribute
			print 'node.attrib[%s]:%s' % ('attr_name',node.attrib['attr_name']))
			keyPath = node.attrib['attr_name']

xml 에 namespace 가 들 어 있 는 구덩이
xml 파일 에 namespace 가 있 으 면 Element Tree 는 namespace 의 이름 을 수정 합 니 다. 보통 ns0 같은 것 으로 바 꿉 니 다. 변경 되 기 를 원 하지 않 으 면 이렇게 합 니 다.
XML_NS_NAME = 'my_ns'
XML_NS_VALUE = 'http://xxx'
ElementTree.register_namespace(XML_NS_NAME, XML_NS_VALUE)  # parse    

namespace 가 있 을 때 namespace 를 바 꿔 야 하 는 노드 를 찾 습 니 다. 예 를 들 어 하나의 attr 는: my 입 니 다.ns: name, 그러면 Element Tree 내부 에서 {로 해 석 됩 니 다.http://xxx} name, 그래서 찾 을 때 도 {를 사용 해 야 합 니 다.http://xxx} name 을 찾 을 수 있 습 니 다.
변환 함수 추가:
#xml namespace                 ,       
def ParseNameSpace(src, nsName, nsValue):
	if src.find(nsName) != -1:
		dst = src.replace('%s:' % nsName, '{%s}' % nsValue)
		print 'ns src:%s dst:%s' % (src, dst)
		return dst

	return src

좋은 웹페이지 즐겨찾기