使用 Python 在 SQL 服务器数据库中保存文件时保留 XML 版本

Retain XML version when file is saved in SQL Server database using Python

我的 Python 代码提取本地存储的 XML 文件并将其保存在 SQL 服务器数据库中。但是,我看到存储在数据库中的文件缺少初始 XML 版本声明:

<?xml version="1.0" encoding="utf-8"?>

为了保留最初的 XML 版本声明,我看到了 lxml 说明添加参数 xml_declaration=True 的文档。使用此参数,我可以在 python 控制台中看到打印的 XML 版本。但是,当我尝试使用相同的参数将其存储在数据库中时,出现错误:

Type: bytes cannot be serialized exception

谁能帮我解决这个异常?

Python代码:

    print("Connecting..")
    # Establish a connection between Python and SQL Server
    conn = pyodbc.connect('Driver={SQL Server};'
                          'Server=TestServer;'
                          'Database=test;'
                          'Trusted_Connection=yes;')
    print("DB Connected..")

    # Open the workbook and define the worksheet
    path = 'C:\Arelle-master\arelle\plugin\TestPlugin\TestExcel.xlsx'
    book = xlrd.open_workbook(path)
    print("Excel Loaded into xlrd..")

    # Get XML File
    XMLFilePath = open('C:\TestPlugin\HelloWorld.xml')
    x = etree.parse(XMLFilePath)
    print(etree.tostring(x, pretty_print=True, xml_declaration=True)) # Shows correct version of XML file in console.

    CreateTable = """
    create table test.dbo.StoreInfo
    (
     col1 varchar(100),
     col2 varchar(100),
     col3 varchar(100),
     col4 varchar(100),
     MyXML XML

    )
    """

    # execute create table
    cursor = conn.cursor()
    try:
         cursor.execute(CreateTable)
         conn.commit()
    except pyodbc.ProgrammingError:
        pass
    print("Table Created..")

    InsertQuery = """
    INSERT INTO test.dbo.StoreInfo (
        col1,
        col2,
        col3,
        col4,
        XBRLFile
    ) VALUES (?, ?, ?, ?, ?)"""

    # Grab existing row count in the database for validation later
    # cursor.execute("SELECT count(*) FROM test.dbo.StoreInfo")
    # before_import = cursor.fetchone()

    for r in range(1, sheet.nrows):
        col1 = sheet.cell(r, 0).value
        col2 = sheet.cell(r, 1).value
        col3 = sheet.cell(r, 2).value
        col4 = sheet.cell(r, 3).value
        col5 = etree.tostring(etree.tostring(x, xml_declaration=True))  # Code throws exception at this line.

        # Assign values from each row
        values = (col1,col2,col3,col4,col5)

        # Execute SQL Insert Query
        cursor.execute(InsertQuery, values)

异常:

col5 = etree.tostring(etree.tostring(x, xml_declaration=True))  
File "src\lxml\etree.pyx", line 3391, in lxml.etree.tostring

TypeError: Type 'bytes' cannot be serialized.

知道如何解决这个错误吗?

MS SQL Server XML 数据类型不保留 XML 声明序言。它被剥离了。 如果出于任何原因确实需要它,则需要将数据类型更改为 NVARCHAR(MAX)。 XML 数据类型在内部存储为 UTF-16 编码。更准确地说,SQL 服务器正在使用 varbinary(max) 数据类型 在内部,但内容本身是 UTF-16 编码文本。