像表一样在T-SQL中解析xml

时间:2018-10-27 14:23:46

标签: sql sql-server

我有以下xml:

  <product>
        <ean>1234</ean>
        <upc>1234</upc>
        <unit/>
    </product>

我尝试将其解析为以下内容:

   DECLARE @xmlCol XML = '
  <product>
        <ean>1234</ean>
        <upc>1234</upc>
        <unit/>
    </product>'

SELECT
  [upc] = x.t.value('@upc', 'int')
FROM 
  @XmlCol.nodes('/product/upc') as x(t)
  CROSS APPLY x.t.nodes( 'Value' ) AS v(t)

什么是不正确的?

结果为空。应该是upc-1234

3 个答案:

答案 0 :(得分:1)

是您要找的东西

// build items array
var items = [
    {
        src: 'https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg',
        w: 964,
        h: 1024
    },
    {
        src: 'https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg',
        w: 1024,
        h: 683
    }
];

// define options (if needed)
var options = {
         // history & focus options are disabled on CodePen        
    history: false,
    focus: false,

    showAnimationDuration: 0,
    hideAnimationDuration: 0

};

var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init();

甚至

   DECLARE @xmlCol XML = '
  <product>
        <unit>
        <ean>1234</ean>
        <upc>1234</upc>
        </unit>
    </product>'

SELECT @xmlCol.value('(/product/unit/upc)[1]', 'int') Result

答案 1 :(得分:0)

您似乎错过了打开单位<unit>标签

 DECLARE @xmlCol XML = '
  <product>
      <unit>
         <ean>1234</ean>
         <upc>1234</upc>
       </unit>
  </product>'

答案 2 :(得分:0)

您可以尝试以下方法:

SELECT
  [upc] = x.t.value('(upc/text())[1]', 'int')
FROM 
  @XmlCol.nodes('/product') as x(t)

以下内容也将起作用:

SELECT
  [upc] = x.t.value('upc[1]', 'int')
FROM 
  @XmlCol.nodes('/product') as x(t)