サブ要素が親と異なる名前空間にある場合、ElementTreeまたはlxmlに名前空間のコンパクトな表現を取得しようとしています。私は、コンパクトElementTreeまたはlxml名前空間
<country>
<ns0:name xmlns:ns0="urn:test">Canada</ns0:name>
<ns1:population xmlns:ns1="urn:test">34M</ns1:population>
</country>
それは正しいですが:私もこのアプローチを試みた
from lxml import etree
country = etree.Element("country")
name = etree.SubElement(country, "{urn:test}name")
name.text = "Canada"
population = etree.SubElement(country, "{urn:test}population")
population.text = "34M"
etree.register_namespace('tst', 'urn:test')
print(etree.tostring(country, pretty_print=True))
:
ns = {"test" : "urn:test"}
country = etree.Element("country", nsmap=ns)
name = etree.SubElement(country, "{test}name")
name.text = "Canada"
population = etree.SubElement(country, "{test}population")
population.text = "34M"
print(etree.tostring(country, pretty_print=True))
両方のケースでは、私はこのような何かを出すここで基本的な例でありますこれはあまり冗長ではないと思いますが、これは大きなデータセットでは本当の問題になる可能性があります(特に私が 'urn:test'よりもはるかに大きなNSを使用しているため)。
私は「国」は「URN:テスト」の内側にあることでOKだ場合は、名前空間と(上記の最初の例では)ので、同じようにそれを宣言します。
country = etree.Element("{test}country")
その後、私は次のような出力が得られます。
<ns0:country xmlns:ns0="urn:test">
<ns0:name>Canada</ns0:name>
<ns0:population>34M</ns0:population>
</ns0:country>
しかし、私が本当にしたいことはこれです:
<country xmlns:ns0="urn:test">
<ns0:name>Canada</ns0:name>
<ns0:population>34M</ns0:population>
<country>
任意のアイデア?
ありがとう!これは私のために働いた。 –