1

我对 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"))

尽管代码中没有任何错误,但它甚至没有替换节点值。如果这里有什么问题,你能帮我吗?

4

0 回答 0