直接看例子吧,假設一張users表,裡面只有id和Pwd兩個欄位。
1,最簡單的用法:
select * from users for xml auto
得到結果如下:
<users id="walker" pwd="walker" /><users id="walker" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /><users id="walker2" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /><users id="walker3" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /><users id="walker4" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /><users id="walker5" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /><users id="john" pwd="insert time:2010/09/06 11:50:40" /><users id="steph" pwd="insert time:2010/09/06 11:50:40" /><users id="john" pwd="insert time:2010/09/06 11:50:53" /><users id="steph" pwd="insert time:2010/09/06 11:50:53" /><users id="john" pwd="insert time:2010/09/06 11:51:01" /><users id="steph" pwd="insert time:2010/09/06 11:51:01" />
2,每一個資料行產生一個節點的方法(注,此時每個節點的名字預設為row,可用自訂的名字代替,此處為設為users)
select * from users for xml raw ('users')--如果不加(‘users'),則節點名為row
因為我把節點名設成了users,則此時產生的xml資料和上例一模一樣。否則也只有節點名不一樣。
3,path用法:
select id "user/id", pwd "user/pwd" from users for xml path
結果:1,2都是把列作為屬性,path用法則把列變成了節點,並且我順便示範了怎麼去自訂層級關係
<row> <user> <id>walker</id> <pwd>walker</pwd> </user></row><row> <user> <id>walker</id> <pwd>1C3A0B25C3D1C909E2BCB9FE44C2F904</pwd> </user></row><row>
4,EXPLICIT 用法,暫時沒有研究。。。
差不多了,可是正好我用的是linq to xml,用到如下代碼來讀取xml資料:
string sql = "select * from users for xml auto";//結果將以xml格式呈現 SqlDatabase db = DatabaseFactory.CreateDatabase() as SqlDatabase; IEnumerable<string> result = null; DbCommand cmd = db.GetSqlStringCommand(sql); using (var reader = db.ExecuteXmlReader(cmd)) { if (reader.IsStartElement()) { var root = (XElement)XNode.ReadFrom(reader);//linq to xml用法 result = root.Elements("users").Attributes("id").Select(x => x.Value); } return result; }
此時用root.Elements(“users”).attributes(“id”)…取不到值,糾結之下用xml文檔測試,發現能正常取值,才想到,可能是沒有根節點的緣故(C#理解成多個根節點,因為每個節點名都一樣),
經測試,確實如此,那麼如何更改查詢語句呢? 上述所有的查詢語句後面加一個root(‘yourname’)即可,如:
select * from users for xml auto , root ('info')
結果為:
<info> <users id="walker" pwd="walker" /> <users id="walker" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /> <users id="walker2" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /> <users id="walker3" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /> <users id="walker4" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /> <users id="walker5" pwd="1C3A0B25C3D1C909E2BCB9FE44C2F904" /> <users id="john" pwd="insert time:2010/09/06 11:50:40" /> <users id="steph" pwd="insert time:2010/09/06 11:50:40" /> <users id="john" pwd="insert time:2010/09/06 11:50:53" /> <users id="steph" pwd="insert time:2010/09/06 11:50:53" /> <users id="john" pwd="insert time:2010/09/06 11:51:01" /> <users id="steph" pwd="insert time:2010/09/06 11:51:01" /></info>