繁体   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