how to parse xml with special character in sql server

后端 未结 3 1250
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 01:07

I am getting following error when i add < in my xml,

Msg 9455, Level 16, State 1, Line 6 XML parsing: line 4, character 14, illegal qual

相关标签:
3条回答
  • 2021-02-20 01:47

    You need to ensure the XML is valid, so you need to make sure any special characters are encoded.

    e.g.

    DECLARE @MyXML XML
    SET @MyXML = '<SampleXML>
    <Colors>
    <Color1>W &lt; hite</Color1>
    <Color2>Blue</Color2>
    <Color3>Black</Color3>
    <Color4 Special="Light">Green</Color4>
    <Color5>Red</Color5>
    </Colors>
    <Fruits>
    <Fruits1>Apple</Fruits1>
    <Fruits2>Pineapple</Fruits2>
    <Fruits3>Grapes</Fruits3>
    <Fruits4>Melon</Fruits4>
    </Fruits>
    </SampleXML>'
    
    0 讨论(0)
  • 2021-02-20 01:52

    < needs to be specified as &lt; in the XML

    <SampleXML>
    <Colors>
    <Color1>W &lt; hite</Color1>
    <Color2>Blue</Color2>
    <Color3>Black</Color3>
    <Color4 Special="Light">Green</Color4>
    <Color5>Red</Color5>
    </Colors>
    <Fruits>
    <Fruits1>Apple</Fruits1>
    <Fruits2>Pineapple</Fruits2>
    <Fruits3>Grapes</Fruits3>
    <Fruits4>Melon</Fruits4>
    </Fruits>
    </SampleXML>
    

    Update:

    The characters you need to escape in node values are < => &lt; and & => &amp;.
    In attribute values you also need to escape " => &quot; if you use " around your attribute values.

    This is a valid XML:

    <root>
      <item> &lt; > &amp; ' "</item>
      <item att=" &lt; > &amp; ' &quot;" />
    </root>
    

    Try it in a query:

    declare @xml xml =
    '
    <root>
      <item> &lt; > &amp; '' "</item>
      <item att=" &lt; > &amp; '' &quot;" />
    </root>
    '
    
    select @xml.value('(root/item)[1]', 'varchar(20)') as NodeValue,
           @xml.value('(root/item/@att)[1]', 'varchar(20)') as AttValue
    

    Result:

    NodeValue            AttValue
    -------------------- --------------------
     < > & ' "            < > & ' "
    
    0 讨论(0)
  • 2021-02-20 01:59

    Invalid special characters & its substitute in xml

    1. & - &amp;
    2. < - &lt;
    3. > - &gt;
    4. " - &quot;
    5. ' - &#39;
    0 讨论(0)
提交回复
热议问题