检查并修复附加到节点的值lxml.objectify在python中

2024-06-14 03:38:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想修改PyKML,它使用lxml.目标化. 通过跟踪节点追加,将此操作转换为具有默认^{cd1>}行为的字符串。我想捕获列表或元组的附件,并将它们转换为适当的位置分隔线,而不是(xx.xxxx, yy.yyyy)'的

from pykml.factory import GX_ElementMaker as GX

track = GX.Track(id='track_%d' % group_num )
for pt in group:
    when = datetime.datetime.utcfromtimestamp(pt['ts'])
    track.append( KML.when( when ) )  # WHEN?
for pt in group:
    track.append( GX.coord( (pt['x'],pt['y'])) )  # <-- trouble here

谢谢, -库尔特


Tags: 字符串inpt目标fordatetime节点group
1条回答
网友
1楼 · 发布于 2024-06-14 03:38:34

使用命名空间信息创建一个干净的ElementMaker类。然后创建一个以节点名作为方法的子类。在这种方法中,处理所有奇怪的情况。然后创建一个字符串,该字符串将放在节点名位置,并使用该节点名返回clean ElementMaker类的实例。在

http://code.google.com/r/schwehr-pykml/source/browse/src/pykml/factory.py?spec=svn05a10cef3fd3c430389e8aca1313a20da932e565&r=05a10cef3fd3c430389e8aca1313a20da932e565

def indexable_levels(args):
    #print 'args:',args
    levels = 0
    while True:
        if isinstance(args,str): break
        try:
            args = args[0]
            levels += 1
        except:
            break
    #print '   levels ->',levels
    return levels

# Create a factory object for the KML Google Extension namespace
_GX_ElementMakerSimple = objectify.ElementMaker(
    annotate=False,
    namespace=nsmap['gx'],
    nsmap={'gx': nsmap['gx']},
)

class _GX_ElementMaker (objectify.ElementMaker):
    'KML ElementMaker with overloads for custom text payloads like coordinates'
    def coord(self, *args):
        #print 'start coord: "%s"' % (str(args)), type(args), len(args)
        levels = indexable_levels(args)
        if levels == 1 and len(args) == 1:
            # This case is really redundant with the next
            assert isinstance(args[0],str)
            return _GX_ElementMakerSimple.coord(args[0])
        if levels == 1:
            return _GX_ElementMakerSimple.coord(' '.join([str(item) for item in args]))
        if levels == 2:
            # ((-121.583851, 37.386052),)
            assert(len(args)==1)
            return _GX_ElementMakerSimple.coord(' '.join([str(item) for item in args[0] ]))
        assert(False)

# Create a factory object for the KML Google Extension namespace
GX_ElementMaker = _GX_ElementMaker(
    annotate=False,
    namespace=nsmap['gx'],
    nsmap={'gx': nsmap['gx']},
)

相关问题 更多 >