Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.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解析凌乱的XML_Python_Xml - Fatal编程技术网

用Python解析凌乱的XML

用Python解析凌乱的XML,python,xml,Python,Xml,我对编码非常陌生,如果有人能帮我弄清楚如何解析XML文件,那就太棒了。 我正在尝试编写一个python脚本,它将读取在Gnome notes中创建的所有注释,并将其显示在命令行中。我已经有了loadnotes部分,但是我不知道如何解析XML以便它显示文本部分。示例数据如下所示: <?xml version="1.0" encoding="UTF-8"?> <note version="1" xmlns:link=&qu

我对编码非常陌生,如果有人能帮我弄清楚如何解析XML文件,那就太棒了。 我正在尝试编写一个python脚本,它将读取在Gnome notes中创建的所有注释,并将其显示在命令行中。我已经有了loadnotes部分,但是我不知道如何解析XML以便它显示文本部分。示例数据如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<note version="1" xmlns:link="http://projects.gnome.org/bijiben/link" xmlns:size="http://projects.gnome.org/bijiben/size" xmlns="http://projects.gnome.org/bijiben">
  <title>Testnote</title>
  <text xml:space="preserve"><html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" href="Default.css" type="text/css" /><script language="javascript" src="bijiben.js"></script></head><body id="editable" style="color: white;">Some text for the note.</body></html></text>
  <last-change-date>2021-04-01T20:03:08Z</last-change-date>
  <last-metadata-change-date>2021-04-01T20:02:53Z</last-metadata-change-date>
  <create-date>2021-03-29T10:37:14Z</create-date>
  <cursor-position>0</cursor-position>
  <selection-bound-position>0</selection-bound-position>
  <width>0</width>
  <height>0</height>
  <x>0</x>
  <y>0</y>
  <color>rgb(0,0,0)</color>
 <tags/>
  <open-on-startup>False</open-on-startup>

测试笔记
注释的一些文本。
2021-04-01T20:03:08Z
2021-04-01T20:02:53Z
2021-03-29T10:37:14Z
0
0
0
0
0
0
rgb(0,0,0)
假的

在解析之后,我应该只得到“注释的一些文本”部分。我一直在用ElementTree来做这个。虽然我在使用示例中提供的“干净”xml文件时没有问题,但我不知道如何处理此文件。

您可以使用正则表达式提取
主体
标记之间的字符串:

(*)
第一个
*
匹配任何字符,零次或多次,以说明body标记中的任何属性

(.*)
捕获标记之间的任何内容

重新导入
以open('file.xml','r')作为文件:
data=file.read()
x=重新搜索(r“(.*),数据)
打印(x组(1))

应该可以使用ElementTree

从xml.etree导入ElementTree作为ET
数据=“”\
测试笔记
注释的一些文本。
2021-04-01T20:03:08Z
2021-04-01T20:02:53Z
2021-03-29T10:37:14Z
0
0
0
0
0
0
rgb(0,0,0)
假的
'''
tree=ET.fromstring(数据)
nmsp={
“xml”:”http://www.w3.org/1999/xhtml',
}#名称空间前缀分配
打印(tree.find('.//xml:body',namespace=nmsp).text)

您可以发布您到目前为止尝试过的代码吗?您的XML没有“凌乱”的地方(一旦您关闭
note
元素)。有关解析它的好方法,请参阅。避免使用正则表达式解析XML,因为这样的解决方案非常脆弱。谢谢你,这会给它一个机会。我发现我能做的比我想象的更多。虽然我昨天一直在修修补补,但我已经用minidom而不是ElementTree找到了可以接受的解决方案,但我想更熟悉ET:)。