使用XSLT获取嵌套在多个相同标签中的XML值(Python)
<keywords>
<theme>
<themekt>THEME_KEY</themekt>
<key>ONE</key>
<key>TWO</key>
<key>THREE</key>
<key>FOUR</key>
<key>FIVE</key>
</theme>
<theme>
<themekt>KEY_TWO</themekt>
<key>NONE</key>
<key>SOME</key>
<key>VALUE</key>
</theme>
</keywords>
我需要从第一个“theme”标签下的“key”标签中获取值1到5。有办法在不使用xslt转换xml的情况下获取这些值吗?我想不出其他办法,所以我尝试了这个:
<xsl:for-each select="keywords/theme">
<xsl:for-each select="key">
<p><xsl:value-of select="key"/></p>
</xsl:for-each>
</xsl:for-each>
上面的代码在html转换中返回了空的p标签。如果我使用下面的代码,它只会返回每个“theme”标签中的第一个key标签的值(ONE和NONE)。
<xsl:for-each select="keywords/theme">
<p><xsl:value-of select="key"/></p>
</xsl:for-each>
1 个回答
0
使用BeautifulSoup来解析这个xml文件是一种方法:
from bs4 import BeautifulSoup
data = '''
<keywords>
<theme>
<themekt>THEME_KEY</themekt>
<key>ONE</key>
<key>TWO</key>
<key>THREE</key>
<key>FOUR</key>
<key>FIVE</key>
</theme>
<theme>
<themekt>KEY_TWO</themekt>
<key>NONE</key>
<key>SOME</key>
<key>VALUE</key>
</theme>
</keywords>
'''
output = []
soup = BeautifulSoup(data, 'xml')
theme = soup.find('theme')
for key in theme.find_all('key'):
output.append(str(key.text))
print output
这样做会给你返回:
['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']
find
方法会返回你搜索条件的第一个匹配项。在这个例子中,搜索条件是标签名为theme
的元素。如果你想要第二个theme
标签的元素,可以使用soup.find_all('theme')
,这会返回一个包含所有theme
标签的列表,然后你可以通过soup.find_all('theme')[1]
来选择第二个标签。
希望这对你有帮助。