복붙노트

[PYTHON] Python Elementtree로 XMLNS 속성에 액세스 하시겠습니까?

PYTHON

Python Elementtree로 XMLNS 속성에 액세스 하시겠습니까?

ElementTree를 사용하여 어떻게 NS 속성에 접근 할 수 있습니까?

다음과 같이 :

<data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22">

내가 root.get ( 'xmlns')하려고 할 때 나는 아무도, 범주 및 날짜 괜찮아, 어떤 도움을 주셨다.

해결법

  1. ==============================

    1.나는 element.tag이 당신이 찾고있는 것이라고 생각합니다. 예제에 슬래시가 없으므로 불균형으로 해석되지 않습니다. 내 예제에 하나 추가했습니다.

    나는 element.tag이 당신이 찾고있는 것이라고 생각합니다. 예제에 슬래시가 없으므로 불균형으로 해석되지 않습니다. 내 예제에 하나 추가했습니다.

    >>> from xml.etree import ElementTree as ET
    >>> data = '''<data xmlns="http://www.foo.net/a"
    ...                 xmlns:a="http://www.foo.net/a"
    ...                 book="1" category="ABS" date="2009-12-22"/>'''
    >>> element = ET.fromstring(data)
    >>> element
    <Element {http://www.foo.net/a}data at 1013b74d0>
    >>> element.tag
    '{http://www.foo.net/a}data'
    >>> element.attrib
    {'category': 'ABS', 'date': '2009-12-22', 'book': '1'}
    

    xmlns URI를 알고 싶으면 다음과 같은 함수로 나눌 수 있습니다.

    def tag_uri_and_name(elem):
        if elem.tag[0] == "{":
            uri, ignore, tag = elem.tag[1:].partition("}")
        else:
            uri = None
            tag = elem.tag
        return uri, tag
    

    ElementTree의 네임 스페이스와 정규화 된 이름에 대한 자세한 내용은 effbot의 예를 참조하십시오.

  2. ==============================

    2.effbot 네임 스페이스 문서 / 예제를보십시오. 특히 parse_map 함수. 특정 요소에 적용되는 접두사 / URI 매핑을 포함하는 각 요소에 * ns_map * 속성을 추가하는 방법을 보여줍니다.

    effbot 네임 스페이스 문서 / 예제를보십시오. 특히 parse_map 함수. 특정 요소에 적용되는 접두사 / URI 매핑을 포함하는 각 요소에 * ns_map * 속성을 추가하는 방법을 보여줍니다.

    그러나 이는 모든 요소에 ns_map 속성을 추가합니다. 필자의 필요에 따라 요소 조회를 쉽게하고 하드 코딩하지 않는 데 사용되는 모든 네임 스페이스의 글로벌 맵을 원했습니다.

    다음은 내가 생각해 낸 것입니다.

    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
    

    이를 통해 xml 파일을 구문 분석하고 네임 스페이스 매핑을 사용하여 dict을 얻을 수 있습니다. 따라서 다음과 같은 XML 파일 ( "my.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 네임 스페이스를 사용하고 dc : creator와 같은 요소에 대한 정보를 얻을 수 있습니다.

    >>> 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'
    
  3. ==============================

    3.이 시도:

    이 시도:

    import xml.etree.ElementTree as ET
    import re
    import sys
    
    with open(sys.argv[1]) as f:
        root = ET.fromstring(f.read())
        xmlns = ''
        m = re.search('{.*}', root.tag)
        if m:
            xmlns = m.group(0)
        print(root.find(xmlns + 'the_tag_you_want').text)
    
  4. from https://stackoverflow.com/questions/1953761/accessing-xmlns-attribute-with-python-elementree by cc-by-sa and MIT license