为什么' ['被视为XmlElement名称的一部分?

时间:2014-12-03 23:22:02

标签: c# sqlite xml-serialization xmldocument innertext

我正在尝试编写一个方法来查询任何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可以看出:

enter image description here

这是否(表中包含“[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

Curioser和curiouser:我的更新的问题是我有一个愚蠢的鹅类型(“&gt;”应该是“&lt;”)。但即使修复了这个问题,我也有例外:

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;
}

...但仍然得到相同的错误信息和xml结果,详见Upate 2。

1 个答案:

答案 0 :(得分: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();
        }
    }