2015-10-04 30 views
0

我遇到了一個SQLite數據庫中的XML結構,它帶有兩個名稱空間。當沒有屬性名稱存在時,如何引用'floatnumber'(在第二個ns後面)?從C#中的SQLite數據庫讀取名稱空間的xml數據

<?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到XML),但沒有成功。

從C#中的xml讀'floatnumber'(數據庫列'值')的最佳方法是什麼?

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() 
    {} 
} 

我的第一篇文章在這裏。 Tom

回答

0

從提供的XML anyType確實不是有一個命名空間。它確實定義了兩個名稱空間q1d1p1,但它們不用於引用該元素。下面的示例使用XPath expression來獲取元素。您也可以使用Linq to 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); 
+0

謝謝富 「但anyType的[內容()= 'floatnumber']」,因爲 'floatnumber' 將無法工作始終由一個以kByte表示SharePoint備份大小的數字號碼佔用。對不起,可能是我描述那個元素不夠。 – tomx64

+0

將字符串轉換爲double時的NullReferenceException,因爲's'IsNullOrEmpty。 – tomx64

0

使用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; 

     } 
    } 
}​ 
+0

親愛的jdweng,非常感謝!這是工作。 – tomx64