-1

我正在尝试编写一个方法来查询任何 SQLite 表并将其内容作为 xml 返回:

// Get any table's contents as XML; caveat: table can have at most 25 columns (this can be increased if necessary)
string IHHSDBUtils.GenericSaveDataAndReturnAsXML(string DBTableName)
{
    String xmlOutput = String.Empty;
    String qry = String.Format("SELECT * FROM {0}", DBTableName);
    try // catch
    {
        using (SQLiteConnection conn = new SQLiteConnection(HHSUtils.GetDBConnection()))
        {
            conn.Open();
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
            doc.AppendChild(dec); // Create the root element
            XmlElement root = doc.CreateElement("Command");
            doc.AppendChild(root);

            try
            {
                using (SQLiteCommand cmd = new SQLiteCommand(qry, conn))
                {
                    using (SQLiteDataReader rdr = cmd.ExecuteReader())
                    {
                        int colCount = rdr.FieldCount;
                        while (rdr.Read())
                        {
                            // outer val
                            XmlElement tblRec = doc.CreateElement(DBTableName);

                            if (colCount > 0)
                            {
                                String firstCol = rdr[0].ToString();
                                XmlElement _firstCol = doc.CreateElement(rdr[0].ToString()); // 
Will this return the right val?
                                _firstCol.InnerText = firstCol;
                                tblRec.AppendChild(_firstCol);
                            }

                            if (colCount > 1)
                            {
                                String secondCol = rdr[1].ToString();
                                XmlElement _secondCol = doc.CreateElement(rdr[1].ToString());
                                _secondCol.InnerText = secondCol;
                                tblRec.AppendChild(_secondCol);
                            }

                            . . .

                            if (colCount > 25)
                            {
                                String twentysixthCol = rdr[25].ToString();
                                XmlElement _twentysixthCol = 
doc.CreateElement(rdr[25].ToString());
                                _twentysixthCol.InnerText = twentysixthCol;
                                tblRec.AppendChild(_twentysixthCol);
                            }

                            root.AppendChild(tblRec);
                        } // while            
                    } // using (SQLiteDataReader
                } // using (SQLiteCommand
            }
            finally
            {
                xmlOutput = doc.OuterXml;
                doc.Save(String.Format("{0}.xml", DBTableName));
            }
        } // using (SQLiteConnection
    } //  try..catch
    catch (Exception ex)
    {
        String msgInnerExAndStackTrace = String.Format(
            "{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, ex.InnerException, 
ex.StackTrace);
        ExceptionLoggingService.Instance.WriteLog(String.Format("From 
HHSDBUtils.GenericSaveDataAndReturnAsXML: {0}", msgInnerExAndStackTrace));
    }
    return xmlOutput;
}

我向这个方法传递了一个少于 25 列(准确地说是 16 列)的表的名称,像这样调用它(测试):

MessageBox.Show(hhsdbutils.GenericSaveDataAndReturnAsXML("Inventory"));

但是,我没有取回一个格式良好的 xml 块,而是取回了这个令人毛骨悚然的公报:

The '[' character, hexadecimal value 0x5B, cannot be included in a name.; Inner Ex: ; Stack 
Trace: at System.Xml.XmlDocument.CheckName(String name)
   at System.Xml.XmlElement..ctor(XmlName name, Boolean empty, XmlDocument doc)
   at System.Xml.XmlDocument.CreateElement(String prefix, String localName, String namespaceURI)
   at System.Xml.XmlDocument.CreateElement(String name)
   at HHS.SQLiteHHSDBUtils.HHS.IHHSDBUtils.GenericSaveDataAndReturnAsXML(String DBTableName)

我确实有一些用括号括起来的占位符 val,从 LINQPad 可以看出:

在此处输入图像描述

这是(在表中有诸如“[CRVid]”之类的值)问题吗?如果是这样,我还必须防止在列值中出现哪些其他“奇数”字符:“{”、“}”、“(”、“)”等?

更新

我在 thumbmunkey 的推动下对代码进行了优雅化(背上有一只猴子):

string IHHSDBUtils.GenericSaveDataAndReturnAsXML(string DBTableName)
{
    String xmlOutput = String.Empty;
    String qry = String.Format("SELECT * FROM {0}", DBTableName);
    try // catch
    {
        using (SQLiteConnection conn = new SQLiteConnection(HHSUtils.GetDBConnection()))
        {
            conn.Open();
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
            doc.AppendChild(dec); // Create the root element
            XmlElement root = doc.CreateElement("Command");
            doc.AppendChild(root);

            // Note that to set the text inside the element,
            // you use .InnerText instead of .Value (which will throw an exception).
            // You use SetAttribute to set attribute
            try
            {
                using (SQLiteCommand cmd = new SQLiteCommand(qry, conn))
                {
                    using (SQLiteDataReader rdr = cmd.ExecuteReader())
                    {
                        // outer val
                        XmlElement tblRec = doc.CreateElement(DBTableName);
                        String colName;
                        XmlElement _colName;

                        int colCount = rdr.FieldCount;

                        for (int i = 0; i < colCount; i++)
                        {
                            rdr.Read();
                            colName = rdr[i].ToString();
                            _colName = doc.CreateElement(colName); // Will this return the right 
val?
                            _colName.InnerText = colName;
                            tblRec.AppendChild(_colName);
                        }

                        root.AppendChild(tblRec);
                    } // using (SQLiteDataReader
                } // using (SQLiteCommand
            }
            finally
            {
                xmlOutput = doc.OuterXml;
                doc.Save(String.Format("{0}.xml", DBTableName));
            }
        } // using (SQLiteConnection
    } //  try..catch
    catch (Exception ex)
    {
        String msgInnerExAndStackTrace = String.Format(
            "{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, ex.InnerException, 
ex.StackTrace);
        ExceptionLoggingService.Instance.WriteLog(String.Format("From 
HHSDBUtils.GenericSaveDataAndReturnAsXML: {0}", msgInnerExAndStackTrace));
    }
    return xmlOutput;
}

...但是现在,尽管由于某种原因异常消失了,但返回的 val 不包含表中的记录。我所看到的是:

<?xml version="1.0"?>
<Command>
<Inventory/>
</Command>

?

更新 2

好奇者和好奇者:我的更新的问题是我有一个愚蠢的鹅类型(>”,它应该是“<”)。但即使修复了这个问题,我也会遇到一个例外:

Date: 2/21/2009 12:54:12 AM
Message: From HHSDBUtils.GenericSaveDataAndReturnAsXML: No current row; Inner Ex: ; Stack 
Trace: at System.Data.SQLite.SQLiteDataReader.CheckValidRow()
   at System.Data.SQLite.SQLiteDataReader.GetValue(Int32 i)
   at System.Data.SQLite.SQLiteDataReader.get_Item(Int32 i)
   at HHS.SQLiteHHSDBUtils.HHS.IHHSDBUtils.GenericSaveDataAndReturnAsXML(String DBTableName)

...并且返回的唯一 xml 是:

<?xml version="1.0"?>
<Command/>

???

更新 3

我将代码更改为:

string IHHSDBUtils.GenericSaveDataAsXML(string DBTableName)
{
    String xmlOutput = String.Empty;
    String qry = String.Format("SELECT * FROM {0}", DBTableName);
    try // catch
    {
        using (SQLiteConnection conn = new SQLiteConnection(HHSUtils.GetDBConnection()))
        {
            conn.Open();
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
            doc.AppendChild(dec); // Create the root element
            XmlElement root = doc.CreateElement("Command");
            doc.AppendChild(root);

            // Note that to set the text inside the element,
            // you use .InnerText instead of .Value (which will throw an exception).
            // You use SetAttribute to set attribute
            try
            {
                using (SQLiteCommand cmd = new SQLiteCommand(qry, conn))
                {
                    using (SQLiteDataReader rdr = cmd.ExecuteReader())
                    {
                        //if (!rdr.HasRows) return; <= won't know this yet
                        // outer val
                        XmlElement tblRec = doc.CreateElement(DBTableName);
                        String colName;
                        XmlElement _colName;

                        while (rdr.Read())
                        {
                            int colCount = rdr.FieldCount;

                            for (int i = 0; i < colCount; i++)
                            {
                                colName = rdr[i].ToString();
                                _colName = doc.CreateElement(colName); // Will this return the right val?
                                _colName.InnerText = colName;
                                tblRec.AppendChild(_colName);
                                rdr.Read();
                            }
                            root.AppendChild(tblRec);
                        } // while (rdr.Read())
                    } // using (SQLiteDataReader
                } // using (SQLiteCommand
            }
            finally
            {
                xmlOutput = doc.OuterXml;
                doc.Save(String.Format("{0}.xml", DBTableName));
            }
        } // using (SQLiteConnection
    } //  try..catch
    catch (Exception ex)
    {
        String msgInnerExAndStackTrace = String.Format(
            "{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, ex.InnerException, ex.StackTrace);
        ExceptionLoggingService.Instance.WriteLog(String.Format("From HHSDBUtils.GenericSaveDataAndReturnAsXML: {0}", msgInnerExAndStackTrace));
    }
    return xmlOutput;
}

...但仍会得到与 Upate 2 中详述的相同的 err msg 和 xml 结果。

4

1 回答 1

1

这个怎么样:

    static string GenerateXmlFromTable(string tableName, bool useAttribute)
    {
        XmlDocument document = new XmlDocument();
        XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", null, null);
        document.AppendChild(declaration);

        XmlElement rootElement = document.CreateElement("Command");
        document.AppendChild(rootElement);

        using (SQLiteConnection connection = new SQLiteConnection("Data source=SqlLite.db"))
        {
            connection.Open();

            string query = string.Format("Select * from {0}", tableName);

            using(SQLiteCommand command = new SQLiteCommand(query, connection))
            {
                using(SQLiteDataReader reader = command.ExecuteReader())
                {
                    while(reader.Read())
                    {
                        XmlElement recordElement = document.CreateElement(tableName);
                        rootElement.AppendChild(recordElement);

                        for(int index = 0; index < reader.FieldCount; index++)
                        {
                            if (useAttribute)
                            {
                                recordElement.SetAttribute(reader.GetName(index), reader.GetValue(index).ToString());
                            }
                            else
                            {
                                XmlElement valueElement = document.CreateElement(reader.GetName(index));
                                valueElement.InnerText = reader.GetValue(index).ToString();

                                recordElement.AppendChild(valueElement);
                            }
                        }
                    }
                }
            }
        }

        using(StringWriter stringWriter = new StringWriter(new StringBuilder()))
        using(XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter))
        {
            xmlWriter.Formatting = Formatting.Indented;

            document.Save(xmlWriter);

            return stringWriter.ToString();
        }
    }
于 2014-12-04T02:07:13.853 回答