6

i am trying to extract values from xml. i am getting problem when xml has attribute. like following Stored Procedure

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 ;
1
  • What is the problem here on extracting ? Commented May 10, 2013 at 6:30

2 Answers 2

11

To get a value of an element with attribute columntype="0"

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

Output:

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

SQLFiddle

Sign up to request clarification or add additional context in comments.

1 Comment

What if I have this XML: <items> <item> <value1>Single Line Text_01</value> <value2>Single Line Text_12341</value> <value3>Single Line Text_21</value> <value4>Single Line Text_31</value> <value5>Single Line Text_41</value> </item> </items> How can I extract values individually in this scenario?
0

Following code will print value of columntype and value :

 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 ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.