簡體   English   中英

從C#中的SQLite數據庫讀取具有名稱空間的xml數據

[英]Read xml data with namespaces from SQLite database in C#

我遇到了來自帶有兩個名稱空間的SQLite數據庫的XML結構。 沒有屬性名稱時,如何引用“ floatnumber”(在第二個ns后面)?

<?xml version="1.0" encoding="utf-8"?>
<anyType xmlns:q1="http://www.w3.org/2001/XMLSchema"
         d1p1:type="q1:string" 
         xmlns:d1p1="http://www.w3.org/2001/XMLSchema-instance">
   floatnumber
 </anyType>

直接將https://system.data.sqlite.org/的 v1.0.98.0包連接到SQLite數據庫。 我一直在玩XmlReader和XDocument(LINQ-to-XML),但沒有成功。

在C#中從xml讀取“ floatnumber”(數據庫列“ Value”)的最佳方法是什么?

using (SQLiteCommand sqlcmd = new SQLiteCommand())
{
    sqlcmd.Connection = connect;
    sqlcmd.CommandText = sqlquery;
    SQLiteDataReader rdr = null;
    try
    {
        rdr = sqlcmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (rdr.Read())
        {
            string xmlstr = rdr["Value"].ToString();
            Console.WriteLine(xmlstr);                  // gives whole xml structure

            /* code to get floatnumber from xml */
        }
    }
    catch ()
    {}
}

我的第一篇文章在這里。 湯姆

從提供的XML anyType 沒有命名空間。 它確實定義了兩個命名空間q1d1p1但是它們不用於引用該元素。 下面的示例使用XPath表達式獲取元素。 您還可以使用Linq到XML

Using System.Xml;

var doc = new XmlDocument();
doc.LoadXml(xmlstr);
var floatnumber = doc.SelectSingleNode("anyType[content() = 'floatnumber']");

更新資料

string s = doc.SelectSingleNode("anyType").Value;
double d = XmlConvert.ToDouble(s);

使用XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlstr =
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<anyType xmlns:q1=\"http://www.w3.org/2001/XMLSchema\"" +
                      " d1p1:type=\"q1:string\"" +
                      " xmlns:d1p1=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                      "floatnumber" +
               "</anyType>";

            XDocument doc = XDocument.Parse(xmlstr);
            XElement anyType = (XElement)doc.FirstNode;
            XNamespace ns = anyType.Name.Namespace;
            XNamespace q1 = anyType.Attributes().Where(x => x.Name.LocalName == "q1").FirstOrDefault().Name.Namespace;
            XNamespace type = anyType.Attributes().Where(x => x.Name.LocalName == "type").FirstOrDefault().Name.Namespace;
            XNamespace d1p1 = anyType.Attributes().Where(x => x.Name.LocalName == "d1p1").FirstOrDefault().Name.Namespace;

            string floatnumber = anyType.Value;

        }
    }
}​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM