XML解析:由于xml

时间:2019-07-05 19:46:29

标签: sql-server xquery

我有一个存储在变量中的xml。我的xml有一个空节点,这不允许我运行代码。当我执行上述代码时,出现此错误。

Msg 9436,第16级,状态1,第2行 XML解析:第12行,字符15,结束标记与开始标记不符

DECLARE @INPUTXML XML = 
'<Lineitems>
  <Lineitem>
    <Ticker>TER</Ticker>
    <ID>0</ID>
    <LineItem>Net Revenue</LineItem>
    <XFundCode>TRIN</XFundCode>
    <UserID>TDP</UserID>
  </Lineitem>
  <Lineitem>
    <Ticker>TER</Ticker>
    <ID>0</ID>
    </LineItem>
    <XFundCode>XXP</XFundCode>
    <UserID>TDP</UserID>    
  </Lineitem>
</Lineitems>';

DECLARE @Ticker  AS VARCHAR(MAX)
    , @ID        AS INT
    , @Lineitem  AS VARCHAR(MAX)
    , @XFundCode AS VARCHAR(MAX)
    , @UserID    AS VARCHAR(MAX);

-- count total number of items
DECLARE @i INT
    , @cnt INT = @INPUTXML.value('count(/Lineitems/Lineitem)', 'INT');

-- loop through XML item by item
SET @i = 1;
WHILE @i <= @cnt 
BEGIN

      SELECT @Ticker = col.value('(Ticker/text())[1]','VARCHAR(MAX)')
         , @ID = col.value('(ID/text())[1]','INT')
         , @Lineitem = nullif('',col.value('(LineItem/text())[1]','VARCHAR(MAX)'))
         , @XFundCode = col.value('(XFundCode/text())[1]','VARCHAR(MAX)')
         , @UserID = col.value('(UserID/text())[1]','VARCHAR(MAX)')
      FROM @INPUTXML.nodes('/Lineitems/Lineitem[position() = sql:variable("@i")]') AS tab(col);

      -- do whatever needed in the loop here
      Print @Lineitem

   SET @i += 1;
END

0 个答案:

没有答案