2015-04-21 26 views
0

我正在使用PyKML創建幾個KML文件,並且遇到了一些奇怪的行爲,我希望有人能夠解釋它。下面重現該問題:PyKML:將地標附加到多個KML文檔

from lxml import etree 
from pykml.factory import KML_ElementMaker as KML 

doc1 = KML.kml(KML.Document()) 
doc2 = KML.kml(KML.Document()) 

p = KML.Placemark() 

doc1.Document.append(p) 
doc2.Document.append(p) 

print etree.tostring(etree.ElementTree(doc1),pretty_print=True) 
print etree.tostring(etree.ElementTree(doc2),pretty_print=True) 

這裏是輸出:

<kml xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://www.opengis.net/kml/2.2"> 
    <Document/> 
</kml> 

<kml xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://www.opengis.net/kml/2.2"> 
    <Document> 
    <Placemark/> 
    </Document> 
</kml> 

地點標記顯示了第二份文件中,而不是在第一。 就好像地標一次只能附加到一個文件一樣。

如果我重新排列最後幾行如下,事情的工作。

doc1.Document.append(p) 
print etree.tostring(etree.ElementTree(doc1),pretty_print=True) 

doc2.Document.append(p) 
print etree.tostring(etree.ElementTree(doc2),pretty_print=True) 

和輸出:

<kml xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://www.opengis.net/kml/2.2"> 
    <Document> 
    <Placemark/> 
    </Document> 
</kml> 

<kml xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://www.opengis.net/kml/2.2"> 
    <Document> 
    <Placemark/> 
    </Document> 
</kml> 

但是這需要我的代碼,我希望能避免重大重組。

我懷疑我錯過了PyKML,lxmlelementtree乃至Python的工作原理。有人能解釋一下可能發生的事情嗎?

回答

1

(部分答案 - 仍然希望一個解釋!)

如果我做的:

from copy import deepcopy 
doc1.Document.append(deepcopy(p)) 
doc2.Document.append(deepcopy(p)) 

工作的事情。但仍然,etree.tostring對輸入對象doc1doc2做什麼?就好像他們被改變了一樣。