使用lxm解析XML

2024-10-03 21:31:59 发布

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

我有以下需要解析的XML。我的主要问题似乎是我不能让斯廷吉奥工作。看起来我无法加载模块;我想我甚至不知道如何显示它已正确加载?以下是作为对http请求的响应返回的xml:

<response method="switchvox.currentCalls.getList">
    <result>
            <current_calls total_items="3">
                            <current_call id="SIP/6525-b59313c8" from_caller_id_name="user1" from_caller_id_number="user1_ext" to_caller_id_name="callee1" to_caller_id_number="callee1_num"  start_time="2011-06-30 15:44:17" duration="346" state="talking" provider="Internal" format="g722-&gt;g722" />
                            <current_call id="SIP/4476-b595a0a0" from_caller_id_name="user2" from_caller_id_number="user1_ext" to_caller_id_name="callee2" to_caller_id_number="callee2_num"  start_time="2011-06-30 15:48:44" duration="79" state="talking" provider="VCG_B" format="g722-&gt;ulaw" />
                            <current_call id="SIP/4483-0aa41320" from_caller_id_name="user3" from_caller_id_number="user1_ext" to_caller_id_name="callee3" to_caller_id_number="callee3_num"  start_time="2011-06-30 15:47:54" duration="129" state="talking" provider="VCG_B" format="g722-&gt;ulaw" />
            </current_calls>
    </result>

目标是将每个“current_call”的每个属性都放入自己的变量中,这样我就可以将它们转储到其他地方的表中。除非我能把它们储存在记忆里什么的?我真正想做的就是把它们再保存一个周期,或者直到我再也看不到那个特定的“id”(我可以假设通话已经结束)。在

我能做点什么吗

^{pr2}$

我相信有更好的方法来做这个!在


Tags: tonamefromidnumbertimecurrentcall
1条回答
网友
1楼 · 发布于 2024-10-03 21:31:59
from lxml import etree

xml_string = """
<response method="switchvox.currentCalls.getList">
    <result>
            <current_calls total_items="3">
                            <current_call id="SIP/6525-b59313c8" from_caller_id_name="user1" from_caller_id_number="user1_ext" to_caller_id_name="callee1" to_caller_id_number="callee1_num"  start_time="2011-06-30 15:44:17" duration="346" state="talking" provider="Internal" format="g722-&gt;g722" />
                            <current_call id="SIP/4476-b595a0a0" from_caller_id_name="user2" from_caller_id_number="user1_ext" to_caller_id_name="callee2" to_caller_id_number="callee2_num"  start_time="2011-06-30 15:48:44" duration="79" state="talking" provider="VCG_B" format="g722-&gt;ulaw" />
                            <current_call id="SIP/4483-0aa41320" from_caller_id_name="user3" from_caller_id_number="user1_ext" to_caller_id_name="callee3" to_caller_id_number="callee3_num"  start_time="2011-06-30 15:47:54" duration="129" state="talking" provider="VCG_B" format="g722-&gt;ulaw" />
            </current_calls>
    </result>
</response>
"""

tree = etree.fromstring(xml_string)

for call in tree.xpath('.//current_call'):
    print call.attrib

给出:

^{pr2}$

相关问题 更多 >