SQL Server 2008粉碎XML数据 - 无法获取rowset中的元素文本!

时间:2010-01-15 05:48:44

标签: sql-server xml sql-server-2008

请考虑这个简单的例子。我无法得到状态元素'red'或'blue'的文字请帮助!!!!!这让我很沮丧

DECLARE @xml XML;

SET @xml = '<capitals>
  <state name="Alabama" 
    abbreviation="AL" 
    capital="Montgomery" >red</state>
  <state name="Alaska" 
    abbreviation="AK" 
    capital="Juneau" >blue</state>
  <state name="Arizona" 
    abbreviation="AZ" 
    capital="Phoenix" >green</state>
</capitals>';

SELECT Node.value('@name', 'varchar(100)') AS Name,
  Node.value('@abbreviation', 'varchar(2)') AS Abbreviation,
  Node.value('@capital', 'varchar(100)') AS Capital
FROM @xml.nodes('/capitals/state') TempXML (Node);

2 个答案:

答案 0 :(得分:4)

你只需要使用。获取元素的内部文本。您也可以使用text()[1]here中有关于xPath的非常好的教程和示例。

DECLARE @xml XML; 

SET @xml = '<capitals> 
  <state name="Alabama"  
    abbreviation="AL"  
    capital="Montgomery" >red</state> 
  <state name="Alaska"  
    abbreviation="AK"  
    capital="Juneau" >blue</state> 
  <state name="Arizona"  
    abbreviation="AZ"  
    capital="Phoenix" >green</state> 
</capitals>'; 

SELECT Node.value('@name', 'varchar(100)') AS Name, 
  Node.value('@abbreviation', 'varchar(2)') AS Abbreviation, 
  Node.value('@capital', 'varchar(100)') AS Capital,
  Node.value('.', 'varchar(100)') AS Color 
FROM @xml.nodes('/capitals/state') TempXML (Node); 

答案 1 :(得分:1)

我想我很傻:

 Node.value('.','varchar(100)') AS PoliticalDisposition