Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python lxml循环遍历所有标记_Python_Xml_Dictionary_Lxml - Fatal编程技术网

python lxml循环遍历所有标记

python lxml循环遍历所有标记,python,xml,dictionary,lxml,Python,Xml,Dictionary,Lxml,我有一个dict将每个xml标记映射到一个dict键。我想循环遍历xml中的每个标记和文本字段,并将其与另一个dict中的相关dict键值进行比较 <2gMessage> <Request> <pid>daemon</pid> <emf>123456</emf> <SENum>2041788209</SENum> <MM&g

我有一个dict将每个xml标记映射到一个dict键。我想循环遍历xml中的每个标记和文本字段,并将其与另一个dict中的相关dict键值进行比较

<2gMessage>
    <Request>
        <pid>daemon</pid>
        <emf>123456</emf>
        <SENum>2041788209</SENum>
        <MM>
            <MID>jbr1</MID>
            <URL>http://jimsjumbojoint.com</URL>
        </MM>
        <AppID>reddit</AppID>
        <CCS>
            <Mode>
                <SomeDate>true</CardPresent>
                <Recurring>false</Recurring>
            </Mode>
            <Date>
                <ASCII>B4788250000028291^RRR^15121015432112345601</ASCII>
            </Date>
            <Amount>100.00</Amount>
        </CCS>
    </Request>
</2gMessage>
但是,这只打印作为请求的直接子项的标记,我希望能够访问子项上的子项(如果它是同一循环中的实例)。我不想硬编码值,因为标记和结构可以更改

您可以尝试使用iter功能。它将遍历所有子元素。长度的比较是只打印那些没有子项的:

像这样的完整脚本:

from lxml import etree
tree = etree.parse('xmlfile')
for tag in tree.iter():
    if not len(tag):
        print (tag.tag, tag.text)
收益率:

pid daemon
emf 123456
SENum 2041788209
MID jbr1
URL http://jimsjumbojoint.com
AppID reddit
CardPresent true
Recurring false
ASCII B4788250000028291^RRR^15121015432112345601
Amount 100.00
你可以试试iter的功能。它将遍历所有子元素。长度的比较是只打印那些没有子项的:

像这样的完整脚本:

from lxml import etree
tree = etree.parse('xmlfile')
for tag in tree.iter():
    if not len(tag):
        print (tag.tag, tag.text)
收益率:

pid daemon
emf 123456
SENum 2041788209
MID jbr1
URL http://jimsjumbojoint.com
AppID reddit
CardPresent true
Recurring false
ASCII B4788250000028291^RRR^15121015432112345601
Amount 100.00

我试图运行您的代码,但出现了错误。除此之外,xml的格式也不好。你试过了吗?非常直观的DOM导航。Beauty Soup位于流行的Python解析器(如lxml和html5lib)之上,允许您尝试不同的解析策略或以速度换取灵活性。除此之外,xml的格式也不好。你试过了吗?非常直观的DOM导航。BeautifulSoup位于流行的Python解析器(如lxml和html5lib)之上,允许您尝试不同的解析策略或以速度换取灵活性。谢谢,这正是我想要的!谢谢,正是我想要的!