이펙트 네임 스페이스 문서/예제를 살펴보십시오. 구체적으로는 parse_map 기능입니다. 특정 요소에 적용되는 접두사/URI 매핑을 포함하는 각 요소에 * ns_map * 속성을 추가하는 방법을 보여줍니다.
그러나 이는 모든 요소에 ns_map 속성을 추가합니다. 필자의 필요에 따라 요소 조회를 쉽게하고 하드 코딩하지 않는 데 사용되는 모든 네임 스페이스의 글로벌 맵을 원했습니다. XML 파일을 구문 분석하고 네임 스페이스 매핑으로 딕셔너리를 얻을 수 있습니다 이것으로
import elementtree.ElementTree as ET
def parse_and_get_ns(file):
events = "start", "start-ns"
root = None
ns = {}
for event, elem in ET.iterparse(file, events):
if event == "start-ns":
if elem[0] in ns and ns[elem[0]] != elem[1]:
# NOTE: It is perfectly valid to have the same prefix refer
# to different URI namespaces in different parts of the
# document. This exception serves as a reminder that this
# solution is not robust. Use at your own peril.
raise KeyError("Duplicate prefix with different URI found.")
ns[elem[0]] = "{%s}" % elem[1]
elif event == "start":
if root is None:
root = elem
return ET.ElementTree(root), ns
:
는 여기에 내가 무엇을 최대 온입니다. 그래서, 당신은 ("my.xml") 다음과 같은 XML 파일이있는 경우 :
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dc="http://purl.org/dc/elements/1.1/"\
>
<feed>
<item>
<title>Foo</title>
<dc:creator>Joe McGroin</dc:creator>
<description>etc...</description>
</item>
</feed>
</rss>
당신은 XML을 namepaces를 사용하고 직류와 같은 요소에 대한 정보를 얻을 수있을 것입니다 : 작성자 :
을
>>> tree, ns = parse_and_get_ns("my.xml")
>>> ns
{u'content': '{http://purl.org/rss/1.0/modules/content/}',
u'dc': '{http://purl.org/dc/elements/1.1/}'}
>>> item = tree.find("/feed/item")
>>> item.findtext(ns['dc']+"creator")
'Joe McGroin'
나는 당신의 질문에 대답 할 수 없다. 그러나 며칠 동안이 단점에 대해 고민하면서 나는 현재의 ElementTree API를 사용하는 것이 불가능하다고 주장 할 준비가되어있다. 내 응용 프로그램에서 xmlns : xlink 특성이 이미 루트 요소에 있었는지 여부를 감지하고 필요하지 않으면 추가해야했습니다. xmlns 속성이 이미 존재하는지 테스트하는 것은 불가능합니다. ElementTree는 시도 할 경우 두 번 추가하면됩니다. 대부분의 XML 소비자에서 동일한 요소에 0 또는 2 개의 동일한 xmlns 특성이 오류를 발생시키기 때문에 ElementTree를 사용하기가 매우 어렵습니다. –