3

I have the next code:

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)

This works fine, and the selected XML field have the next format:

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

How can I take that field and save it in a new XML file in a directory...?

This is the script for my database:

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
1
  • 1
    Simply save the row string to file. Commented Mar 4, 2016 at 18:39

1 Answer 1

3

Solved, in the next way...

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)
Sign up to request clarification or add additional context in comments.

2 Comments

To make it work with Python 3, change with with open("example.xml", "wb") as f
Also if someone encounters error with encoding, I used: f.write(xml_str.encode('utf8'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.