【问题标题】:parsing string that uses xml like tags in a fast way快速解析使用类似xml标签的字符串
【发布时间】:2019-04-11 10:16:38
【问题描述】:

我有一个包含这种格式的数据的文件,看起来像没有根标记的 XML

<Item>
     <ItemNumber>123</ItemNumber>
        <ItemData>
           very cool item
        </itemData>
        <ItemData>
         more informaion about this item
        </ItemData>
</Item>
<Item>
     <ItemNumber>123</ItemNumber>
        <ItemData>
           very cool item
        </itemData>
        <ItemData>
         more informaion about this item
        </ItemData>
</Item>

我有很多这种格式的文件(1800+ 每个文件 1M-5M),我需要解析它们 以一种允许我访问标签之间的数据的方式, 标签中的可选数据以快速的方式。 我尝试使用beautifulSoup,但效率不高, 也尝试过 lxml,但因为我没有根标签,所以我不会犯很多错误,而且我无法更改文件

需要使用python3

【问题讨论】:

    标签: python xml string python-3.x parsing


    【解决方案1】:

    使用lxml.html中的fromstring函数作为described in example here,

    with open("d:/b.xml") as f:
        read_xml = fromstring(f.read())
        for tag in read_xml:
            print(tag.text_content().strip())
    

    给你,

    123
    
               very cool item
    
    
             more informaion about this item
    123
    
               very cool item
    
    
             more informaion about this item
    

    【讨论】:

    • 文件没有.xml后缀所以打不开
    • 只要把代码中的后缀改一下就行了
    • 我像你说的那样尝试并得到这个:错误 FileNotFoundError:[Errno 2] 没有这样的文件或目录:'b.xml'
    • 你在哪里存档?您需要在代码中提供正确的文件路径,而不仅仅是复制粘贴我的代码
    • 文件不是 XML 文件,他们用 XML 之类的标签编写,只是没有根标签
    猜你喜欢
    • 2015-07-03
    • 2023-02-22
    • 1970-01-01
    • 2020-03-26
    • 2020-02-28
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多