2017-07-08 95 views
0

的元素值,我需要在Python文件中像這樣來改變一個子元素值:Python的 - 煩惱與改變XML文件

<stock> 
    <product code="002"> 
    <title>Electric</title> 
    <tracks>Wild flower,Peace dog,Electric ocean</tracks> 
    <price>30.50</price> 
    <pictures>002.gif</pictures> 
    <entry>12/06/2017</entry> 
    <artist>The Cult</artist> 
    <descr>Nice rock album</descr> 
    <genre>Hard Rock</genre> 
    <extras>Astbury,vocals Duffy,guitar Stewart,bass Warner,drums</extras> 
    <copies>8</copies> 
    </product> 
</stock> 

我需要減少副本的數量,我寫下了這個方法,所述ElementTree庫的文檔以下:

@staticmethod 
def decrease_copies(prod_id): 
    from store.classes.Product import Product 
    tree = XMLUtil.parse_file(PROD_FILENAME) 
    bought = Product.fetch_from_xml(prod_id) 
    left_copies = int(bought.copies) - 1 
    for prod in XMLUtil.get_xml_root(PROD_FILENAME).iter('product'): 
     if prod.attrib.get('code') == prod_id: 
      cps = prod.find('copies') 
      cps.text = str(left_copies) 
      print(tree) 
      tree.write(PROD_FILENAME) 
      break 

目的bought是在XML文件包含作爲字段所有標籤的產品類的一個實例,並且PROD_FILENAME是該文件的路徑。名爲parse_fileXMLUtil中的方法返回該文件的樹。

我沒有收到任何錯誤,但是當我模擬購買時文件沒有被更改。有人能告訴我什麼是錯的嗎?

回答

0

我使用lxml。通常不會更改原始文件。當您完成所有操作時,創建一個新文件並寫入它。測試下面的代碼。工作正常。

from lxml import etree 
f = '''<stock> 
    <product code="002"> 
    <title>Electric</title> 
    <tracks>Wild flower,Peace dog,Electric ocean</tracks> 
    <price>30.50</price> 
    <pictures>002.gif</pictures> 
    <entry>12/06/2017</entry> 
    <artist>The Cult</artist> 
    <descr>Nice rock album</descr> 
    <genre>Hard Rock</genre> 
    <extras>Astbury,vocals Duffy,guitar Stewart,bass Warner,drums</extras> 
    <copies>8</copies> 
    </product> 
</stock>''' 
root = etree.XML(f) 
product = root.find(".//product[@code]") 
cope = product.find("./copies") 
cope.text = str(9) 
doc = etree.ElementTree(root) 
outFile = open('D://test.xml', 'wb') 
doc.write(outFile)