我是Python的新手并且坚持到了一个点。我试图用MS SQL Server中的相应值替换XML文档中的选择性节点。我应该只使用minidom来实现同样的目标。数据库表包含波兰语中的买方信息,该信息是单一的,我应该用波兰数据替换现有XML中的英语信息。 以下是XML文档的结构,其中应该发生更改:
<INVPARTNER>
<INVOICE_BUYER>XXXXX</INVOICE_BUYER> (Unique Customer ID)
<INVOICE_PAYERNO>92254</INVOICE_PAYERNO>
<INVOICE_BUYERVATID>BLAH</INVOICE_BUYERVATID>
<buyer1>ABC</buyer1> (Customer name 1: DB Value CUSTNAME1)
<buyer2/> (Customer name 2: DB Value CUSTNAME2)
<buyer3>XYZ</buyer3> (Customer name 3: DB Value CUSTADDR1)
<buyer4/> (Customer name 4: DB Value CUSTADDR2)
<buyer5>PQR</buyer5>
<buyer6>ITALY</buyer6>
<buyer7/>
<buyer8></buyer8>
<buyer9/>
<buyer10/>
我已经编写了以下代码来实现相同的目标但未能这样做:
import pyodbc
from xml.dom.minidom import parse
import os
docTypes = {'INVOICE':['INVOICE_BUYER', 'INVOICE_CONSIGNEE']}
changeValues = {'INVOICE':{"buyer1":'CUSTNAME1', "buyer2":'CUSTNAME2', "buyer3":'CUSTADDRESS1', "buyer4":'CUSTADDRESS2'}}
dom = parse("Print.xml")
type = dom.getElementsByTagName('DocumentID')[0].childNodes[0].nodeValue
print type
i = 0
CONN_STR = 'DSN=dsn;;DB=test_DB;UID=usr;PWD=passwrd'
db = pyodbc.connect(CONN_STR)
c = db.cursor()
print docTypes['INVOICE']
if docTypes.has_key(type):
#iterator = len(docTypes[type])
for i in range(0,len(docTypes[type])):
for tag in dom.getElementsByTagName(docTypes[type][i]):
name = tag.childNodes[0]
c.execute (u"select CUSTOMER, ADDRESSTYPE, CUSTNAME1, CUSTNAME2, CUSTADDRESS1, CUSTADDRESS2 from CUSTADDR_UC where 'CUSTOMER' = ('%u')", name.nodeValue)
rows = c.fetchall()
for key in changeValues[type].iterkeys():
print dom.getElementsByTagName(key)[0].toxml()
for row in rows:
if dom.getElementsByTagName(key)[0].toxml() is not None:
change = dom.getElementsByTagName(key)[0].toxml()
change.nodeValue = unicode(row.changeValue[type][key])
open("D:\\Shantanu\\done2.xml","w").write(dom.toxml("utf-8"))
虽然代码中没有任何错误,但它甚至没有替换节点值。如果这里有什么问题,你能帮帮我吗?