2016-02-01 35 views
1

我有一系列的我的驱动器上的XML文件,我想要做以下:如何使用lxml从磁盘加载.xml文件作为元素树?

  • 加载到lxml去的元素树和使用XPath解析
  • 加载另一个XML文件的元素树,并与解析XPath查找正确的位置附加信息
  • 我从一系列XML文件应设为变量,这样我就可以追加回到大.xml文件
之前运行的结果有一定的逻辑分析的信息

我在文件类型的一些问题/将XML文件作为元素树正确加载,以便它们可以通过lxml进行操作。我尝试了几种不同的方法,但仍遇到各种问题。目前存在的问题如下:

TypeError: Argument '_parent' has incorrect type (expected lxml.etree._Element, got list)

from lxml import etree 
from lxml import html 
import requests 

file = 'bgg.xml' 
# parse the xml file from disk as an element tree in lxml? 
treebgg = etree.parse(file) 

# create a list of IDs to iterate through from the bgg.xml file 
gameList = treebgg.xpath("//root/BGG/@ID") 

# iterate through the IDs 
for x in reversed(gameList): 
    url = 'https://somewhere.com/xmlapi/' + str(x) 
    page = requests.get(url) 
    # pull an xml file from a web url and turn it into an element tree in lxml 
    tree = html.fromstring(page.content) 
    # set my root variable so I can append children to this location 
    root = tree.xpath("//root/BGG[@ID=x]") 
    name = tree.xpath("//somewhere/name[@primary='true']" 
    # append child info into bgg.xml 
    child = etree.SubElement(root, "Name") 
    child.text = name 

# write bgg.xml back to file 

回答

1

获取bgg.xml树的根:

rootbgg = treebgg.getroot() 

,并用它的孩子追加到:

child = etree.SubElement(rootbgg, "Name") 

I'm having another problem...how do I select the correct element? I don't want to append to the root of the xml file itself.

现在,您将需要重新设计你遍历元素的方式:

gameList = treebgg.xpath("//root/BGG") 

# iterate through the IDs 
for game in reversed(gameList): 
    url = 'https://somewhere.com/xmlapi/' + game.attrib["id"] 
    page = requests.get(url) 
    tree = html.fromstring(page.content) 
    # TODO: get the name 

    # append child info into bgg.xml 
    child = etree.SubElement(game, "Name") 
    child.text = name 
+0

我试图rootbgg = treebgg.getroot(),但我有一个问题...我该如何选择正确的元素?我不想追加到xml文件本身的根目录。 您好 #append这里 Aro

+0

@Aro与样品代码更新进行。我希望我明白你想要做的是什么。 – alecxe

+0

谢谢!这解决了我的问题。 – Aro