解析XML和只存储一个属性而不是全部

问题描述:

我有一个非常大的XML与很多人,每个人有一个唯一的ID存储在他的XML节点中的属性,我的问题是我如何只存储该节点的愿望属性(在这种情况下,第一个),并非所有的属性,到目前为止我的代码是:解析XML和只存储一个属性而不是全部

if os.path.isfile('library.xml'): 
    xml = ET.parse('library.xml') 
    root = xml.getroot() 
    create_file = 'coverage.xml' 
    openfile = open(create_file, 'a') 
    openfile.write('<?xml version="1.0" encoding="ISO-8859-1"?>') 
    for child in root: 
     for analyst in child: 
      analystId = [] 
      analystId.append(analyst.attrib) #<- Trying to append only first one as a dictionary with [1], analystId.append(analyst.attrib[1]), but it didn't work 
      print str(analystId) 
    openfile.close() 
else: 
    print "Library xml not found in " + str(search_path) + ". Please check if file exist." 

所以尽可能去,现在它需要所有的属性,并将其储存在analystId ,你只需要第一个(在这种情况下)。

后多次尝试是我想出办法在我的情况:

好像我没有做在欲望节点的欲望属性的匹配,所以我做了欲望节点的搜索和从指定的属性附加欲望ID。 如果有人正在寻找一些信息,这对我有用。所以我的代码如下所示:

if os.path.isfile('library.xml'): 
    xml = ET.parse('library.xml') 
    root = xml.getroot() 
    create_file = 'coverage_rbc.xml' 
    openfile = open(create_file, 'a') 
    openfile.write('<?xml version="1.0" encoding="ISO-8859-1"?>') 
    for child in root: 
     for analyst in child.findall('Analyst'): <- Got the desire node correctly 
      analystId = [] 
      ids = analyst.get('id') <- Got the correct value of desired attribute 
      analystId.append(ids) <- append the attribute 
      print str(analystId) 
    openfile.close() 
else: 
    print "Library xml not found in " + str(search_path) + ". Please check if file exist." 

无论如何都要提前致谢。

+1

您应该添加示例XML以供我们理解。 –

+0

谢谢,但我知道了。 – Victor

+0

如果您发布了您尝试过的以及您发现了什么,那将会很棒。它使您能够从需要帮助的地方为社区做出贡献。 –

看起来像我没有搜索到所有的欲望节点,并没有正确追加属性。我是Python的n00b,但这对我有用:

到达愿望节点后,我用child.findall('节点')来搜索特定的属性,然后我得到了使用孩子的愿望属性.get('attributeName')并将其附加到我的列表中。

希望我的解释有助于某人,如果不是的话,对不起。

Regards