如何在Python 2.6中删除XML字符串中的空格和换行符?我尝试了以下包:
etree:这个片段保留了原始的空格:
xmlStr = '''<root>
<head></head>
<content></content>
</root>'''
xmlElement = xml.etree.ElementTree.XML(xmlStr)
xmlStr = xml.etree.ElementTree.tostring(xmlElement, 'UTF-8')
print xmlStr
Run Code Online (Sandbox Code Playgroud)
我不能使用提供method参数的Python 2.7 .
minidom:同样的:
xmlDocument = xml.dom.minidom.parseString(xmlStr)
xmlStr = xmlDocument.toprettyxml(indent='', newl='', encoding='UTF-8')
Run Code Online (Sandbox Code Playgroud) 我有一个包含从http请求返回的XML数据的字符串.
我正在使用ElementTree来解析数据,然后我想以递归方式搜索一个元素.
根据这个问题,我只能递归搜索result.findall()if result是类型ElementTree而不是类型Element.
现在xml.etree.ElementTree.fromstring(),用于解析字符串,返回一个Element对象,而xml.etree.ElementTree.parse()用于解析文件,返回一个ElementTree对象.
我的问题是:我如何解析字符串并获取ElementTree实例?(没有像写临时文件那样疯狂)
此XML文件命名为example.xml:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>14.0.0</modelVersion>
<groupId>.com.foobar.flubber</groupId>
<artifactId>uberportalconf</artifactId>
<version>13-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Environment for UberPortalConf</name>
<description>This is the description</description>
<properties>
<birduberportal.version>11</birduberportal.version>
<promotiondevice.version>9</promotiondevice.version>
<foobarportal.version>6</foobarportal.version>
<eventuberdevice.version>2</eventuberdevice.version>
</properties>
<!-- A lot more here, but as it is irrelevant for the problem I have removed it -->
</project>
Run Code Online (Sandbox Code Playgroud)
如果我加载example.xml并使用ElementTree解析它,我可以看到它的命名空间http://maven.apache.org/POM/4.0.0.
>>> from xml.etree import ElementTree
>>> tree = ElementTree.parse('example.xml')
>>> print tree.getroot()
<Element '{http://maven.apache.org/POM/4.0.0}project' at 0x26ee0f0>
Run Code Online (Sandbox Code Playgroud)
我还没有找到一种方法来调用从而Element无需解析str(an_element)元素来获取命名空间.似乎必须有更好的方法.
我在xml文件中有这个char:
<data>
<products>
<color>fumè</color>
</product>
</data>
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下代码生成ElementTree的实例:
string_data = open('file.xml')
x = ElementTree.fromstring(unicode(string_data.encode('utf-8')))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 185: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
(注意:位置不准确,我从较大的位置采样了xml).
怎么解决?谢谢
我从外部源接收xml字符串,其中包含未经授权的用户贡献内容.
以下xml字符串给出了ParseError cElementTree:
>>> print repr(s)
'<Comment>dddddddd\x08\x08\x08\x08\x08\x08_____</Comment>'
>>> import xml.etree.cElementTree as ET
>>> ET.XML(s)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
ET.XML(s)
File "<string>", line 106, in XML
ParseError: not well-formed (invalid token): line 1, column 17
Run Code Online (Sandbox Code Playgroud)
有没有办法让cElementTree不抱怨?
因为我第二次遇到这个烦人的问题,我觉得这个问题会有所帮助.
有时候我必须从XML文档中获取Elements,但是这样做的方法很尴尬.
我想知道一个python库,它可以实现我想要的,一种优雅的方式来表示我的XPath,一种在前缀中自动注册命名空间的方法,或者在内置XML实现中的隐藏首选项,或者在lxml中完全删除命名空间.澄清之后,除非你已经知道我想要什么:)
实施例-doc的:
<root xmlns="http://really-long-namespace.uri"
xmlns:other="http://with-ambivalent.end/#">
<other:elem/>
</root>
Run Code Online (Sandbox Code Playgroud)
ElementTree API是唯一内置的(我知道)提供XPath查询.但它需要我使用"UNames".这看起来像这样:/{http://really-long-namespace.uri}root/{http://with-ambivalent.end/#}elem
如您所见,这些都非常冗长.我可以通过以下方式缩短它们:
default_ns = "http://really-long-namespace.uri"
other_ns = "http://with-ambivalent.end/#"
doc.find("/{{{0}}}root/{{{1}}}elem".format(default_ns, other_ns))
Run Code Online (Sandbox Code Playgroud)
但是,这是双方{{{丑陋}}}和脆弱的,因为http…end/#≅ http…end#≅ http…end/≅ http…end和我是谁知道哪个变种会用吗?
此外,lxml支持名称空间前缀,但它既不使用文档中的名称前缀,也不提供处理默认名称空间的自动方法.我仍然需要从每个命名空间中获取一个元素以从文档中检索它.命名空间属性不会保留,因此也无法自动从这些属性中检索它们.
有一种与命名空间无关的XPath查询方式,但它在内置实现中既详细又丑陋且不可用: /*[local-name() = 'root']/*[local-name() = 'elem']
我想找到一个库,选项或通用的XPath变形函数,通过输入以下内容来实现上述示例...
/root/elem/root/other:elem...加上可能是一些我确实想要使用文档前缀或剥离命名空间的语句.
进一步澄清:虽然我目前的用例很简单,但将来我将不得不使用更复杂的用例.
谢谢阅读!
用户samplebias将我的注意力引向了py-dom-xpath ; 正是我在寻找什么.我的实际代码现在看起来像这样:
#parse the document into a DOM tree
rdf_tree = xml.dom.minidom.parse("install.rdf")
#read the default namespace and prefix from the root node
context = xpath.XPathContext(rdf_tree)
name = context.findvalue("//em:id", rdf_tree)
version …Run Code Online (Sandbox Code Playgroud) 我有一个XML文档,我想在其中搜索一些元素,如果它们符合某些标准,我想删除它们
但是,我似乎无法访问元素的父级,以便我可以删除它
file = open('test.xml', "r")
elem = ElementTree.parse(file)
namespace = "{http://somens}"
props = elem.findall('.//{0}prop'.format(namespace))
for prop in props:
type = prop.attrib.get('type', None)
if type == 'json':
value = json.loads(prop.attrib['value'])
if value['name'] == 'Page1.Button1':
#here I need to access the parent of prop
# in order to delete the prop
Run Code Online (Sandbox Code Playgroud)
有没有办法可以做到这一点?
谢谢
我的XML解析函数的简化版本在这里:
import xml.etree.cElementTree as ET
def analyze(xml):
it = ET.iterparse(file(xml))
count = 0
for (ev, el) in it:
count += 1
print('count: {0}'.format(count))
Run Code Online (Sandbox Code Playgroud)
这会导致Python耗尽内存,这并没有多大意义.我实际存储的唯一东西是count,一个整数.为什么这样做:

看到内存和CPU使用率突然下降?这是Python的惊人崩溃.至少它给了我一个MemoryError(取决于我在循环中做了什么,它给了我更多随机错误,比如一个IndexError)和堆栈跟踪而不是段错误.但为什么会崩溃?
有没有办法在python ElementTree中定义默认/未固定的命名空间?这似乎不起作用......
ns = {"":"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("version", ns))
Run Code Online (Sandbox Code Playgroud)
这也不是:
ns = {None:"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("version", ns))
Run Code Online (Sandbox Code Playgroud)
这样做,但后来我必须为每个元素添加前缀:
ns = {"mvn":"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("mvn:version", ns))
Run Code Online (Sandbox Code Playgroud)
在OSX上使用Python 3.5.
编辑:如果答案是"不",你仍然可以获得赏金:-).我只想要一个花费大量时间使用它的人明确的"不".
如何通过使用ElementTree访问NS属性?
具有以下内容:
<data xmlns="http://www.foo.net/a" xmlns:a="http://www.foo.net/a" book="1" category="ABS" date="2009-12-22">
Run Code Online (Sandbox Code Playgroud)
当我尝试root.get('xmlns')我回来没有,类别和日期都很好,任何帮助赞赏..
elementtree ×10
python ×10
xml ×5
encoding ×1
lxml ×1
memory-leaks ×1
namespaces ×1
parsing ×1
python-2.6 ×1
python-3.x ×1
unicode ×1
utf-8 ×1
xpath ×1