屬性此XML(在SQL 2005 XML列):把XML從SQL
<doc>
<a>1</a>
<b ba="1" bb="2" bc="3" />
<c bd="3"/>
<doc>
我想能夠檢索屬性的名稱(BA,BB,BC,BD)而不是使用C#窗體表單應用程序中的值。
屬性此XML(在SQL 2005 XML列):把XML從SQL
<doc>
<a>1</a>
<b ba="1" bb="2" bc="3" />
<c bd="3"/>
<doc>
我想能夠檢索屬性的名稱(BA,BB,BC,BD)而不是使用C#窗體表單應用程序中的值。
有兩種方法在你的情況下做到這一點:
如果你可以創建存儲在您的SQL服務器上的程序:
您可以創建拆卸XML轉換爲列的存儲過程,並很容易SELECT
他們並讓C#應用程序處理它,就好像它是一個包含列和行的表。
如果您不能:
可以拆開使用SqlXml
從System.Xml
命名空間C#中的XML。
這兩種方法都用實例很好地說明如下:
http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx#sql2k5xml_topic4
嘗試是這樣的 - 第一種方法會從數據庫加載XML字符串(調整連接字符串和查詢到自己的數據庫,服務器,表,列名),第二個方法將解析從數據庫加載到基於你有你的前一個問題的答案的屬性名稱的列表,XML字符串:
static void Main(string[] args)
{
string xmlContent = GrabStringFromDatabase(1);
List<string> attributeNames = ParseForAttributeNames(xmlContent);
Console.WriteLine("Your XML attributes are: {0}", string.Join(",", attributeNames.ToArray()));
}
private static string GrabStringFromDatabase(int ID)
{
string result = string.Empty;
string connection = "server=(local);database=test;integrated security=SSPI";
string query = "SELECT XmlContent FROM dbo.TestXml WHERE ID = @ID";
using(SqlConnection _con = new SqlConnection(connection))
using (SqlCommand _cmd = new SqlCommand(query, _con))
{
_cmd.Parameters.Add("@ID", SqlDbType.Int).Value = ID;
_con.Open();
result = _cmd.ExecuteScalar().ToString();
_con.Close();
}
return result;
}
private static List<string> ParseForAttributeNames(string xmlContent)
{
List<string> attributeNames = new List<string>();
XDocument xmlDoc = XDocument.Parse(xmlContent);
var nodeAttrs = xmlDoc.Descendants().Select(x => x.Attributes());
foreach (var attrs in nodeAttrs)
{
foreach (var attr in attrs)
{
attributeNames.Add(attr.Name.LocalName);
}
}
return attributeNames;
}
有你不是剛剛問過這個嗎? http://stackoverflow.com/questions/4237327/getting-attributes-and-values-of-xml-using-c – 2010-11-21 11:35:27
是的,但這並不是確切的答案,它可以幫助我......我希望我能說清楚現在 – salman 2010-11-21 11:36:55
你的Xml的Salman格式不正確,''應該在最後,你可以在我爲你發佈的代碼中跳過'attr.Value',如果你修復你當前的xml問題,你會得到'ba,bb ,bc,bd'也應該刪除額外的輸出。 – 2010-11-21 12:07:38