c#数据表writexml控制列名称

问题描述 投票:0回答:1

在我的程序中,我正在写入SQLite DB表的XML内容。一切都很好,但是输出格式不适合我。如何在元素中应用自己的名称。因为如果我从SQLite加载到DataTable并尝试通过WriteXML保存,则列的名称位于Elements的名称中。我想把Element的名称作为element的属性。请看一下,这是我的代码。

我的C#代码:

namespace SQLiteDemo
{
    internal class Program
    {   
        private const string DatabaseFile = "j.db";
        private const string DatabaseSource = "data source=" + DatabaseFile;

        private static void Main(string[] args)
        {
            // Create the file which will be hosting our database
            if (!File.Exists(DatabaseFile))
            {
                SQLiteConnection.CreateFile(DatabaseFile);
            }

            // Connect to the database 
            using (var connection = new SQLiteConnection(DatabaseSource))
            {
                // Create a database command
                using (var command = new SQLiteCommand(connection))
                {
                    connection.Open();

                    // Select and display database entries
                    command.CommandText = "Select * FROM DB_company_5000";

                    var ds = new DataTable();

                    ds.Load(command.ExecuteReader());
                    ds.WriteXml("jj.xml");

                    connection.Close(); // Close the connection to the database
                    Console.Read();
                }
            }
        }
    }
}

我的输出是:

<DB_company_5000>
    <ID>3</ID>
    <Name>Velin Ivan</Name>
    <Adress>Vamberská 273</Adress>
    <City>London 18</City>
    <TEL>NULL</TEL>
    <EXT>NULL</EXT>
</DB_company_5000>

所需的输出:

    <table name="DB_company_5000">
        <column name="ID">1</column>
        <column name="Name">Velin Ivan</column>
        <column name="Adress">Vamberská 273</column>
        <column name="City">London 18</column>
        <column name="TEL">NULL</column>
        <column name="EXT">NULL</column>
    </table>

感谢您的回复

c# xml sqlite converters
1个回答
0
投票

由于基本XML只是字符串数据,我们可以使用简单的字符串替换来解决此问题。它不是特别优雅,但我认为它可以回答问题:

string xml = @"<DB_company_5000>
                 <ID>3</ID>
                 <Name>Velin Ivan</Name>
                 <Adress>Vamberská 273</Adress>
                 <City>London 18</City>
                 <TEL>NULL</TEL>
                 <EXT>NULL</EXT>
               </DB_company_5000>";

xml = xml.Replace("<DB_company_5000>", "<table name=\"DB_company_5000\">");
xml = xml.Replace("</DB_company_5000>", "</table>");
xml = xml.Replace("<ID>", "<column name=\"ID\">");
xml = xml.Replace("</ID>", "</column>");
// ETC...
© www.soinside.com 2019 - 2024. All rights reserved.