sql query xml values returning NULL

后端 未结 2 1643
Happy的楠姐
Happy的楠姐 2021-01-19 10:09

I\'m not experienced with the xml structure and need a start-point to how I can retrieve the values from xml structure below.

I fetch the <

2条回答
  •  梦毁少年i
    2021-01-19 10:56

    Your xml includes a namespace xmlns="http://www.webserviceX.NET/", which is the default namespace. You must either declare it or use a wildcard for the prefix.

    With XML there are some best practices:

    • Be as specific as possible
    • Only forward navigation
    • Important If the creation of the XML is under your control change the date and time format to ISO8601. Your formats are culture specific and can easily lead to conversion errors on different systems. Best was a combined value like 2017-05-23T12:37:00

    For your issue there are several approaches:

    DECLARE @xml XML=
    N'
      
        
          ENGI.PA
          13.53
          5/23/2017
          
          
        
      
    ';
    

    --Best approach: XMLNAMESPACES to declare the default namespace

    WITH XMLNAMESPACES(DEFAULT 'http://www.webserviceX.NET/')
    SELECT @xml.value(N'(/string/StockQuotes/Stock/Symbol/text())[1]',N'nvarchar(max)');
    

    --Implicit namespace declaration:

    SELECT @xml.value(N'declare namespace ns="http://www.webserviceX.NET/";
                       (/ns:string/ns:StockQuotes/ns:Stock/ns:Symbol/text())[1]',N'nvarchar(max)');
    

    --Not recommended in most cases, but good for lazy people :-D

    SELECT @xml.value(N'(//*:Symbol)[1]',N'nvarchar(max)');
    

    --If you want to read more values of the same level, you can use .nodes to set the current node to ....

    WITH XMLNAMESPACES(DEFAULT 'http://www.webserviceX.NET/')
    SELECT st.value('(Symbol/text())[1]',N'nvarchar(max)')
          ,st.value('(Last/text())[1]',N'decimal(10,4)')
          --more nodes 
    FROM @xml.nodes(N'/string/StockQuotes/Stock') AS A(st);
    

提交回复
热议问题