Python元素解析未绑定前缀错误

时间:2019-01-17 05:36:27

标签: xml python-3.x elementtree

我想使用python中的Element库将ElementTree附加到现有的xml树中。

我如何尝试做到这一点:

newPhrase2 = '''<d:entry id="{}" d:title="{}">
            <d:index d:value="{}" d:title="{}"/>
            <h1>{}</h1>
            <div class="ODECN">
                <div class="extras">
                    <h2>{}</h2>
                    <div class="phrase">
                    {}
                    {}
                    </div>
                    <p class="ref">See main entry:
                       <a href="x-dictionary:d:entry://{}#uwid1191809650">do</a>
                    </p>
                </div>
            </div>
        </d:entry>
    '''.format(new_id, title, title, title, title, title, odef_ext, defs, source_title)

    b = etree.fromstring(newPhrase2)
    root.append(b)
    tree.write(newXmlPath, xml_declaration=True, encoding='utf-8', short_empty_elements=False)

但出现未绑定前缀错误。

Traceback (most recent call last):File "/Users/chris/PycharmProjects/DictionariesRelated/extract_phrases_ET_version.py", line 127, in <module>
b = etree.fromstring(newPhrase2)File"/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/etree/ElementTree.py", line 1315, in XML
parser.feed(text) xml.etree.ElementTree.ParseError: unbound prefix: line 1, column 0

1 个答案:

答案 0 :(得分:0)

好。我只是通过添加其名称空间来解决它。

newPhrase2 = '''<d:entry xmlns:d="http://www.apple.com/DTDs/DictionaryService-1.0.rng" id="{}" d:title="{}">
            <d:index d:value="{}" d:title="{}"/>
            <h1>{}</h1>
            <div class="ODECN">
                <div class="extras">
                    <h2>{}</h2>
                    <div class="phrase">
                    {}
                    {}
                    </div>
                    <p class="ref">See main entry:
                       <a href="x-dictionary:d:entry://{}#uwid1191809650">do</a>
                    </p>
                </div>
            </div>
        </d:entry>
    '''.format(new_id, title, title, title, title, title, odef_ext, defs, source_title)