如何在python中解析xml以找到以下节点的文本值?

2024-04-28 22:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个示例配置XML文件,如下所示:

<?xml version="1.0"?>
<note> 
    <to>Tove</to> 
    <infoaboutauthor>
      <nestedprofile>
           <aboutme> 
               <gco:CharacterString>I am a 10th grader who likes to play ball.</gco:CharacterString> 
          </aboutme>
      </nestedprofile>
    </infoaboutauthor>
    <date>
        <info_date>
            <date>
               <gco:Date>2003-06-13</gco:Date>
            </date>
            <datetype>
                <datetype attribute="Value">
                </datetype>
            </datetype>
        </info_date>
    </date>
    <from>Jani</from> 
    <heading>Reminder</heading> 
    <body>Don't forget me this weekend!</body> 
  </note>

在python中(尝试使用ElementTree,不确定它是否是最好的)我希望为某些标记获取某些值。我试过:

^{pr2}$

在我上面使用的代码中,当我遇到以下错误时,冒号似乎不起作用:

SyntaxError: prefix 'gco' not found in prefix map

我的目标是

  1. 获取“2003-06-13”标签中的文本
  2. “aboutme”标记中的文本

最好的办法是什么?有什么办法可以抬头看吗gco:字符字符串其中parent等于aboutme?去哪里方便?在

注意:“gco:”前缀是xml的一部分,我必须处理它。如果elementtree不适合这样做,那就可以了。在


Tags: tofrominfodatebodyxmlnotegco
2条回答

首先,你的XML被破坏了。第2行中的-正在破坏解析器。另外,我认为它不喜欢gco:s。您可以使用其他一些XML配置吗?或者这是你无法控制的东西自动生成的吗?在

因此,要使用Python,XML需要的外观如下:

<?xml version="1.0"?>
<note>
    <to>Tove</to>
    <infoaboutauthor>
      <nestedprofile>
           <aboutme>
               <CharacterString>I am a 10th grader who likes to play ball.</CharacterString>
          </aboutme>
      </nestedprofile>
    </infoaboutauthor>
    <date>
        <info_date>
            <date>
               <Date>2003-06-13</Date>
            </date>
            <datetype>
                <datetype attribute="Value">
                </datetype>
            </datetype>
        </info_date>
    </date>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>

下面是实现两个目标的代码:

^{pr2}$

更新

就处理“gco”而言,你可以这样做:

def replace_in_config(old, new):
    with open('config.xml', 'r') as f:
        text = f.read()

    with open('config.xml', 'w') as f:
        f.write(text.replace(old, new))

然后,在执行上述XML操作之前,请运行:

replace_in_config('gco:', '_stripped')

然后在XMl操作完成后(当然,您需要考虑到gco:Date标记现在是stripped_Date和CharacterString标记一样),运行以下命令:

replace_in_config('_stripped', 'gco:')

这将保留原始格式,并允许您使用etree对其进行解析。在

我认为您的XML文档无效,因为尚未定义“gco”命名空间。在

我找不到一种方法来将定义作为parse命令的一部分提供给lxml。您可以按照@mjgpy3的建议操作文档来添加定义或删除前缀。在

另一种方法可能是使用HTML解析器,因为这对它将接受的内容没有那么严格。但是Beaware认为这会改变数据的结构来添加HTML头等等。在

from lxml import etree

Parser = etree.HTMLParser()
XMLDoc = etree.parse(open('C:/Temp/Test.xml', 'r'), Parser)

Elements = XMLDoc.xpath('//characterstring')

for Element in Elements:
    print Element.text

相关问题 更多 >