从mysql中的xml中提取值

时间:2013-05-10 05:44:13

标签: mysql xml database

我正在尝试从xml中提取值。我在xml具有属性时遇到问题。 比如以下存储过程

DELIMITER $$
DROP PROCEDURE IF EXISTS `excel`.`insert_items` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_items`()
BEGIN
SET @xml = '<items><item>
        <value columntype="0">Single Line Text_01</value>
    <value columntype="1">Single Line Text_12341</value>
    <value columntype="2">Single Line Text_21</value>
    <value columntype="3">Single Line Text_31</value>
    <value columntype="4">Single Line Text_41</value>
    </item>
</items>';
SELECT @columntype, ExtractValue(@xml, 'items/item/value[items/item/value/@columntype=0]');    
END $$
DELIMITER ;

2 个答案:

答案 0 :(得分:8)

获取具有属性columntype="0"

的元素的值
SELECT ExtractValue(@xml, 'items/item/value[@columntype=0]') value;

输出:

|               VALUE |
-----------------------
| Single Line Text_01 |

<强> SQLFiddle

答案 1 :(得分:0)

以下代码将打印 columntype 的值:

 DELIMITER $$
    DROP PROCEDURE IF EXISTS `TEST`$$
    CREATE DEFINER=`root`@`localhost` PROCEDURE `TEST`(IN XMLINPUT TEXT)
    BEGIN
    DECLARE VALUECOUNT INT UNSIGNED;
    DECLARE VALUE INT UNSIGNED;
    DECLARE I INT UNSIGNED DEFAULT 1;
    SET VALUECOUNT:=EXTRACTVALUE(XMLINPUT, 'COUNT(/items/item/value)');
    SELECT VALUECOUNT; -- print 5
    WHILE (I <= VALUECOUNT) DO 
        SELECT EXTRACTVALUE(XMLINPUT, '/items/item/value[$I]/@columntype[1]'); -- will print columntype tag
        SELECT EXTRACTVALUE(XMLINPUT, '/items/item/value[$I]'); -- will print value tag     
    SET I:= I+1;
    END WHILE;

    END$$DELIMITER ;