Python XML解析 [英] Python XML Parsing

查看:51
本文介绍了Python XML解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*注意:lxml将无法在我的系统上运行.我希望找到一种不涉及lxml的解决方案.

*Note: lxml will not run on my system. I was hoping to find a solution that does not involve lxml.

我已经阅读了一些此处的文档,并且很难按照我的意愿来进行操作.我想解析一些看起来像这样的XML文件:

I have gone through some of the documentation around here already, and am having difficulties getting this to work how I would like to. I would like to parse some XML file that looks like this:

<dict>
    <key>1375</key>
    <dict>
        <key>Key 1</key><integer>1375</integer>
        <key>Key 2</key><string>Some String</string>
        <key>Key 3</key><string>Another string</string>
        <key>Key 4</key><string>Yet another string</string>
        <key>Key 5</key><string>Strings anyone?</string>
    </dict>
</dict>

在我要操作的文件中,此命令之后还有更多的"dict".我想通读XML并输出看起来像这样的text/dat文件:

In the file I am trying to manipulate, there are more 'dict' that follow this one. I would like to read through the XML and output a text/dat file that would look like this:

1375,某些字符串",另一个字符串",又一个字符串",有人字符串吗?"

1375, "Some String", "Another String", "Yet another string", "Strings anyone?"

...

Eof

** 最初,我尝试使用lxml,但是在尝试使其在我的系统上运行之后,我继续使用DOM.最近,我尝试使用Etree来完成此任务.拜托,因为对所有美好事物的热爱,有人会帮助我吗?我是Python的新手,想学习它的工作原理.我先谢谢你.

** Originally, I tried to use lxml, but after many tries to get it working on my system, I moved on to using DOM. More recently, I tried using Etree to do this task. Please, for the love of all that is good, would somebody help me along with this? I am relatively new to Python and would like to learn how this works. I thank you in advance.

推荐答案

您可以使用

You can use xml.etree.ElementTree which is included with Python. There is an included companion C-implemented (i.e. much faster) xml.etree.cElementTree. lxml.etree offers a superset of the functionality but it's not needed for what you want to do.

@Acorn提供的代码对我来说(Python 2.7,Windows 7)与以下每个导入均相同:

The code provided by @Acorn works identically for me (Python 2.7, Windows 7) with each of the following imports:

import xml.etree.ElementTree as et
import xml.etree.cElementTree as et
import lxml.etree as et
...
tree = et.fromstring(xmltext)
...

您正在使用什么操作系统以及lxml遇到了哪些安装问题?

What OS are you using and what installation problems have you had with lxml?

这篇关于Python XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆