<person>
<user name="david" password="super"><groups>meganfox</groups></user>
<user name="alen" password="boss"><groups>marvik</groups></user>
</person>
我想获得“群组”的文字值。但它总是没有。
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>
没有组文本值。它只打印一个封闭的组。请检查输出
答案 0 :(得分:2)
1)从for groups
到user.set("password"
的整个块需要缩进一个级别.Python的控制流程都是关于缩进的,所以这会将它移到第一个循环中。
2)您是否尝试在新文件中保留组?获得组值后,您不会对其执行任何操作。
答案 1 :(得分:1)
在第二个for循环中用child.
替换root.
!这应该做到!
或者通过第二眼看,它似乎想要制作一个嵌套循环, 但是你的代码没有正确缩进! ; - )
答案 2 :(得分: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