Python - 使用 pyodbc 将 XML 字段从 SQL 服务器转换为 XML 文件

Python - Convert XML field from SQL SERVER into XML FILE using pyodbc

我有下一个代码:

import pypyodbc as pyodbc

cnxn = pyodbc.connect(
    'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=HOLA;UID=sa;PWD=HOLAMUNDO'
)

idPerson = 2

cursor = cnxn.cursor()
cursor.execute('SELECT * FROM prueba WHERE id=?', (idPerson,))
for row in cursor.fetchall():
    print(row)

这很好用,所选的 XML 字段具有以下格式:

<PERSON>
  <INFO>
    <NAME>Charlie</NAME>
    <LASTNAME>Brown</LASTNAME>
  </INFO>
</PERSON>

如何获取该字段并将其保存在目录中的新 XML 文件中...?

这是我的数据库的脚本:

USE [HOLA]
GO
/****** Object:  Table [dbo].[prueba]    Script Date: 04/03/2016 8:29:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[prueba](
    [id] [int] NOT NULL,
    [xml] [xml] NULL,
 CONSTRAINT [PK_prueba] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

已解决,在接下来的方式中...

import pypyodbc as pyodbc
import urllib
from xml.dom.minidom import parse, parseString
xmlpath = "example.xml"

cnxn = pyodbc.connect(
    'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost;DATABASE=HOLA;UID=sa;PWD=HOLAMUNDO'
)

idPerson = 2

cursor = cnxn.cursor()
cursor.execute('SELECT id, xml FROM prueba WHERE id=?', (idPerson,))

for row in cursor.fetchall():
    print row[1]

xml = row[1]

#Generate the xml file from the string
dom = parseString(xml)

# Write the new xml file
xml_str = dom.toprettyxml(indent="  ")
with open("example.xml", "w") as f:
    f.write(xml_str)