0
<person>
<user name="david" password="super"><groups>meganfox</groups></user>
<user name="alen" password="boss"><groups>marvik</groups></user>
</person>

我喜欢获取 "groups" 的文本值。但它总是没有。

import xml.etree.ElementTree as ET

doc    = ET.parse("users.xml")
root = doc.getroot() #Returns the root element for this tree.
root_new  = ET.Element("person") 
for child in root:
    name                = child.attrib['name']
    password             = child.attrib['password']
for groups in child.findall('groups'): #this is not working for me :(
    gpvalue =  groups.text 

    user  = ET.SubElement(root_new, "user") # create subelement in cycle! 
    group = ET.SubElement(user, "groups")
    user.set("name",name)               
    user.set("password",password) 
    group.text = gpvalue

tree = ET.ElementTree(root_new)
tree.write("new.xml")

import sys
tree.write(sys.stdout)

输出得到:(

<person>
    <user name="david" password="super"></groups></user>
    <user name="alen" password="boss"></groups></user>
  </person>

没有组文本值。它的打印只有一个封闭的组。请检查输出

4

3 回答 3

2

for groups1) from to的整个块user.set("password"需要再缩进一级。Python 的控制流程都是关于缩进的,所以这会将它移到第一个循环中。

2)您是否尝试在新文件中保留组?一旦你拥有了 groups 的价值,你就不会对它做任何事情。

于 2012-11-05T05:19:13.953 回答
1

在你的第二个 for 循环中替换child.为!root.这应该做!

或者第二次看它,您似乎想要创建一个嵌套循环,但是您的代码没有正确缩进!;-)

于 2012-11-05T05:13:14.077 回答
1

如果您想在groups不通过用户的情况下获取值,可以使用路径:

>>> root.findall("user")
[<Element 'user' at 0x1004d9f90>, <Element 'user' at 0x1004df0d0>]
>>> root.findall("groups")
[]
>>> root.findall("*/groups")
[<Element 'groups' at 0x1004d9fd0>, <Element 'groups' at 0x1004df190>]
>>> [g.text for g in root.findall("*/groups")]
['meganfox', 'marvik']

但循环似乎对我有用:

>>> for child in root:
...     print child.attrib['name'], child.attrib['password'], 
...     for groups in child.findall("groups"):
...         print groups.text,
...     print
... 
david super meganfox
alen boss marvik
于 2012-11-05T05:15:39.250 回答