本文介绍了ElementTree应该以相同的方式解析字符串和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 关于elementtree的一个不好的设计是它有不同的方式解析 字符串和文件,更糟糕的是它们返回不同的对象: 1)当你解析一个文件,你可以简单地调用parse,它返回一个 元素树,然后你可以在其上应用xpath; 2)要解析一个字符串(xml部分),你可以调用XML或fromstring,但两者都是返回元素而不是elementtree。仅此一点是不好的。更糟糕的是,你需要在使用 xpath之前从这个元素创建一个elementtree。 One bad design about elementtree is that it has different ways parsing astring and a file, even worse they return different objects:1) When you parse a file, you can simply call parse, which returns aelementtree, on which you can then apply xpath;2) To parse a string (xml section), you can call XML or fromstring, but bothreturn element instead of elementtree. This alone is bad. To make it worse,you have to create an elementtree from this element before you can utilizexpath.推荐答案 我没有试过这个,但是你应该能够将你的文本字符串包裹起来 以便它看起来像一个文件使用stringio模块并将 传递给elementtree: http://blog.doughellmann.com/2007/04...cstringio.html - Paddy。 I haven''t tried this, but you should be able to wrap your text stringso that it looks like a file using the stringio module and pass thatto elementtree: http://blog.doughellmann.com/2007/04...cstringio.html - Paddy. ElementTree不支持XPath。如果你的意思是find *()方法支持的更简单的ElementPath 语言,我没有看到为什么 你不能使用它的原因元素。 ElementTree doesn''t support XPath. In case you mean the simpler ElementPathlanguage that is supported by the find*() methods, I do not see a reason whyyou can''t use it on elements. a)在fromstring()周围写一个包装器函数是多么困难,它包裹了一个ElementTree对象中的结果元素并返回它? b)与上述相同:我无法看到你所说的问题。 Stefan a) how hard is it to write a wrapper function around fromstring() that wrapsthe result Element in an ElementTree object and returns it? b) the same as above applies: I can''t see the problem you are talking about. Stefan ElementTree不支持XPath。如果你的意思是find *()方法支持的更简单的元素路径元素 语言,我没有看到原因 为什么 你不能在元素上使用它。 ElementTree doesn''t support XPath. In case you mean the simplerElementPathlanguage that is supported by the find*() methods, I do not see a reasonwhyyou can''t use it on elements. a)在fromstring()周围写一个包装函数是多么困难 包裹 结果ElementTree对象中的元素并将其返回? b)与上述相同:我无法看到你说的问题 about。 Stefan a) how hard is it to write a wrapper function around fromstring() thatwrapsthe result Element in an ElementTree object and returns it?b) the same as above applies: I can''t see the problem you are talkingabout.Stefan 这篇关于ElementTree应该以相同的方式解析字符串和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 23:59