Parse XML to get node value in bash script?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








15















I would like to know how I can get the value of a node with the following paths:



config/global/resources/default_setup/connection/host
config/global/resources/default_setup/connection/username
config/global/resources/default_setup/connection/password
config/global/resources/default_setup/connection/dbname


from the following XML:



<?xml version="1.0"?>
<config>
<global>
<install>
<date><![CDATA[Tue, 11 Dec 2012 12:31:25 +0000]]></date>
</install>
<crypt>
<key><![CDATA[70e75d7969b900b696785f2f81ecb430]]></key>
</crypt>
<disable_local_modules>false</disable_local_modules>
<resources>
<db>
<table_prefix><![CDATA]></table_prefix>
</db>
<default_setup>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[root]]></username>
<password><![CDATA[pass123]]></password>
<dbname><![CDATA[testdb]]></dbname>
<initStatements><![CDATA[SET NAMES utf8]]></initStatements>
<model><![CDATA[mysql4]]></model>
<type><![CDATA[pdo_mysql]]></type>
<pdoType><![CDATA]></pdoType>
<active>1</active>
</connection>
</default_setup>
</resources>
<session_save><![CDATA[files]]></session_save>
</global>
<admin>
<routers>
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
</routers>
</admin>
</config>


Also I want to assign that value to the variable for further use. Let me know your idea.










share|improve this question



















  • 7





    Do not ever use bash to parse structured trees of arbitrary data. Use a real XML parser. I recommend XMLStarlet.

    – Chris Down
    Jul 17 '13 at 15:16












  • stackoverflow.com/questions/893585/how-to-parse-xml-in-bash

    – Ciro Santilli 新疆改造中心996ICU六四事件
    Oct 7 '15 at 10:57











  • Lol, Magento much?

    – siliconrockstar
    Apr 17 '17 at 23:03

















15















I would like to know how I can get the value of a node with the following paths:



config/global/resources/default_setup/connection/host
config/global/resources/default_setup/connection/username
config/global/resources/default_setup/connection/password
config/global/resources/default_setup/connection/dbname


from the following XML:



<?xml version="1.0"?>
<config>
<global>
<install>
<date><![CDATA[Tue, 11 Dec 2012 12:31:25 +0000]]></date>
</install>
<crypt>
<key><![CDATA[70e75d7969b900b696785f2f81ecb430]]></key>
</crypt>
<disable_local_modules>false</disable_local_modules>
<resources>
<db>
<table_prefix><![CDATA]></table_prefix>
</db>
<default_setup>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[root]]></username>
<password><![CDATA[pass123]]></password>
<dbname><![CDATA[testdb]]></dbname>
<initStatements><![CDATA[SET NAMES utf8]]></initStatements>
<model><![CDATA[mysql4]]></model>
<type><![CDATA[pdo_mysql]]></type>
<pdoType><![CDATA]></pdoType>
<active>1</active>
</connection>
</default_setup>
</resources>
<session_save><![CDATA[files]]></session_save>
</global>
<admin>
<routers>
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
</routers>
</admin>
</config>


Also I want to assign that value to the variable for further use. Let me know your idea.










share|improve this question



















  • 7





    Do not ever use bash to parse structured trees of arbitrary data. Use a real XML parser. I recommend XMLStarlet.

    – Chris Down
    Jul 17 '13 at 15:16












  • stackoverflow.com/questions/893585/how-to-parse-xml-in-bash

    – Ciro Santilli 新疆改造中心996ICU六四事件
    Oct 7 '15 at 10:57











  • Lol, Magento much?

    – siliconrockstar
    Apr 17 '17 at 23:03













15












15








15


11






I would like to know how I can get the value of a node with the following paths:



config/global/resources/default_setup/connection/host
config/global/resources/default_setup/connection/username
config/global/resources/default_setup/connection/password
config/global/resources/default_setup/connection/dbname


from the following XML:



<?xml version="1.0"?>
<config>
<global>
<install>
<date><![CDATA[Tue, 11 Dec 2012 12:31:25 +0000]]></date>
</install>
<crypt>
<key><![CDATA[70e75d7969b900b696785f2f81ecb430]]></key>
</crypt>
<disable_local_modules>false</disable_local_modules>
<resources>
<db>
<table_prefix><![CDATA]></table_prefix>
</db>
<default_setup>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[root]]></username>
<password><![CDATA[pass123]]></password>
<dbname><![CDATA[testdb]]></dbname>
<initStatements><![CDATA[SET NAMES utf8]]></initStatements>
<model><![CDATA[mysql4]]></model>
<type><![CDATA[pdo_mysql]]></type>
<pdoType><![CDATA]></pdoType>
<active>1</active>
</connection>
</default_setup>
</resources>
<session_save><![CDATA[files]]></session_save>
</global>
<admin>
<routers>
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
</routers>
</admin>
</config>


Also I want to assign that value to the variable for further use. Let me know your idea.










share|improve this question
















I would like to know how I can get the value of a node with the following paths:



config/global/resources/default_setup/connection/host
config/global/resources/default_setup/connection/username
config/global/resources/default_setup/connection/password
config/global/resources/default_setup/connection/dbname


from the following XML:



<?xml version="1.0"?>
<config>
<global>
<install>
<date><![CDATA[Tue, 11 Dec 2012 12:31:25 +0000]]></date>
</install>
<crypt>
<key><![CDATA[70e75d7969b900b696785f2f81ecb430]]></key>
</crypt>
<disable_local_modules>false</disable_local_modules>
<resources>
<db>
<table_prefix><![CDATA]></table_prefix>
</db>
<default_setup>
<connection>
<host><![CDATA[localhost]]></host>
<username><![CDATA[root]]></username>
<password><![CDATA[pass123]]></password>
<dbname><![CDATA[testdb]]></dbname>
<initStatements><![CDATA[SET NAMES utf8]]></initStatements>
<model><![CDATA[mysql4]]></model>
<type><![CDATA[pdo_mysql]]></type>
<pdoType><![CDATA]></pdoType>
<active>1</active>
</connection>
</default_setup>
</resources>
<session_save><![CDATA[files]]></session_save>
</global>
<admin>
<routers>
<adminhtml>
<args>
<frontName><![CDATA[admin]]></frontName>
</args>
</adminhtml>
</routers>
</admin>
</config>


Also I want to assign that value to the variable for further use. Let me know your idea.







command-line text-processing xml xmllint






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 30 '16 at 0:06









Jeff Schaller

45k1164147




45k1164147










asked Jul 17 '13 at 15:09









MagePsychoMagePsycho

208129




208129







  • 7





    Do not ever use bash to parse structured trees of arbitrary data. Use a real XML parser. I recommend XMLStarlet.

    – Chris Down
    Jul 17 '13 at 15:16












  • stackoverflow.com/questions/893585/how-to-parse-xml-in-bash

    – Ciro Santilli 新疆改造中心996ICU六四事件
    Oct 7 '15 at 10:57











  • Lol, Magento much?

    – siliconrockstar
    Apr 17 '17 at 23:03












  • 7





    Do not ever use bash to parse structured trees of arbitrary data. Use a real XML parser. I recommend XMLStarlet.

    – Chris Down
    Jul 17 '13 at 15:16












  • stackoverflow.com/questions/893585/how-to-parse-xml-in-bash

    – Ciro Santilli 新疆改造中心996ICU六四事件
    Oct 7 '15 at 10:57











  • Lol, Magento much?

    – siliconrockstar
    Apr 17 '17 at 23:03







7




7





Do not ever use bash to parse structured trees of arbitrary data. Use a real XML parser. I recommend XMLStarlet.

– Chris Down
Jul 17 '13 at 15:16






Do not ever use bash to parse structured trees of arbitrary data. Use a real XML parser. I recommend XMLStarlet.

– Chris Down
Jul 17 '13 at 15:16














stackoverflow.com/questions/893585/how-to-parse-xml-in-bash

– Ciro Santilli 新疆改造中心996ICU六四事件
Oct 7 '15 at 10:57





stackoverflow.com/questions/893585/how-to-parse-xml-in-bash

– Ciro Santilli 新疆改造中心996ICU六四事件
Oct 7 '15 at 10:57













Lol, Magento much?

– siliconrockstar
Apr 17 '17 at 23:03





Lol, Magento much?

– siliconrockstar
Apr 17 '17 at 23:03










6 Answers
6






active

oldest

votes


















18














Using bash and xmllint (as given by the tags):



xmllint --version # xmllint: using libxml version 20703

# Note: Newer versions of libxml / xmllint have a --xpath option which
# makes it possible to use xpath expressions directly as arguments.
# --xpath also enables precise output in contrast to the --shell & sed approaches below.
#xmllint --help 2>&1 | grep -i 'xpath'



 sed '1d;$d')"
password="$(echo "cat /config/global/resources/default_setup/connection/password/text()"

# output
# host: localhost
# username: root
# password: pass123
# dbname: testdb



In case there is just an XML string and the use of a temporary file is to be avoided, file descriptors are the way to go with xmllint (which is given /dev/fd/3 as a file argument here):



set +H

xmllint --nocdata --shell /dev/fd/3
set -H


# output
# host: localhost
# username: root
# password: pass123
# dbname: testdb





share|improve this answer


















  • 1





    Man page: xmlsoft.org/xmllint.html

    – Jason Pyeron
    Sep 21 '14 at 15:27


















6














Although there are a lot of answers already, I'll chime in with xml2.



$ xml2 < test.xml
/config/global/install/date=Tue, 11 Dec 2012 12:31:25 +0000
/config/global/crypt/key=70e75d7969b900b696785f2f81ecb430
/config/global/disable_local_modules=false
/config/global/resources/db/table_prefix
/config/global/resources/default_setup/connection/host=localhost
/config/global/resources/default_setup/connection/username=root
/config/global/resources/default_setup/connection/password=pass123
/config/global/resources/default_setup/connection/dbname=testdb
/config/global/resources/default_setup/connection/initStatements=SET NAMES utf8
/config/global/resources/default_setup/connection/model=mysql4
/config/global/resources/default_setup/connection/type=pdo_mysql
/config/global/resources/default_setup/connection/pdoType
/config/global/resources/default_setup/connection/active=1
/config/global/session_save=files
/config/admin/routers/adminhtml/args/frontName=admin


With a little magic you can even set those as variables directly:



$ eval $(xml2 < test.xml | tr '/, ' '___' | grep =)
$ echo $_config_global_resources_default_setup_connection_host
localhost





share|improve this answer






























    3














    The following works when run against your test data:



     read -r host; read -r username; read -r password; read -r dbname; 
    < <(xmlstarlet sel -t -m /config/global/resources/default_setup/connection
    -v ./host -n
    -v ./username -n
    -v ./password -n
    -v ./dbname -n)


    This puts the content into variables host, username, password and dbname.






    share|improve this answer

























    • xmlstarlet: command not found, so this command is not useful to me :(

      – MagePsycho
      Jul 17 '13 at 15:31











    • @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

      – Charles Duffy
      Jul 17 '13 at 15:48












    • @CharlesDuffy is there a way to get the value may be using regex pattern or else?

      – MagePsycho
      Jul 17 '13 at 15:51






    • 5





      @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

      – terdon
      Jul 17 '13 at 15:57






    • 1





      @MagePsycho I was about to post the same link terdon already did. In short: No.

      – Charles Duffy
      Jul 17 '13 at 16:05


















    3














    A pure bash function, just for the unfortunate case when you are not allowed to install anything appropriate. This may, and probably will, fail on more complicated XML:



    function xmlpath()

    local expr="$1//// "
    local path=()
    local chunk tag data

    while IFS='' read -r -d '<' chunk; do
    IFS='>' read -r tag data <<< "$chunk"

    case "$tag" in
    '?'*) ;;
    '!–-'*) ;;
    '![CDATA['*) data="$tag:8:$#tag-10" ;;
    ?*'/') ;;
    '/'?*) unset path[$#path[@]-1] ;;
    ?*) path+=("$tag") ;;
    esac

    [[ "$path[@]" == "$expr" ]] && echo "$data"
    done



    Usage:



    bash-4.1$ xmlpath 'config/global/resources/default_setup/connection/host' < MagePsycho.xml
    localhost


    Known issues:



    • slow

    • searches only by tag names

    • no character entity decoding





    share|improve this answer






























      0














      You can make use of php command line interface coding in bash scripts to handle several complex scripts that actually span over multiple lines of coding. First, try to make your solution using PHP scripts, and then later on pass the parameters using CLI mode. Thus, you can get control over superb usages of XML parsers.



      The environment seems that you can use PHP in client mode via ssh/shell access.



      php -f yourxmlparser.php


      Now, do all the things within your php file. Make use of command line parameters it can take.



      You can even assign that return values to Shell environment to continue rest of your shell scripts.



      And the other way is to use |grep option to match your required value within the xml file, if you are pretty sure of the structure of your xml file that does not change over time.






      share|improve this answer
































        0














        Using xmllint and the --xpath option, it is very easy. You can simply do this:



        XML_FILE=/path/to/file.xml

        HOST=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/host)' $XML_FILE
        USERNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/username)' $XML_FILE
        PASSWORD=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/password)' $XML_FILE
        DBNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/dbname)' $XML_FILE


        If you need to get to an element's attribute, that's also easy using XPath. Imagine you have the file:



        <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <addon id="screensaver.turnoff"
        name="Turn Off"
        version="0.10.0"
        provider-name="Dag Wieërs">
        ..snip..
        </addon>


        The needed shell statements would be:



        VERSION=$(xmllint --xpath 'string(/addon/@version)' $ADDON_XML)
        AUTHOR=$(xmllint --xpath 'string(/addon/@provider-name)' $ADDON_XML)





        share|improve this answer























          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "106"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f83385%2fparse-xml-to-get-node-value-in-bash-script%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          18














          Using bash and xmllint (as given by the tags):



          xmllint --version # xmllint: using libxml version 20703

          # Note: Newer versions of libxml / xmllint have a --xpath option which
          # makes it possible to use xpath expressions directly as arguments.
          # --xpath also enables precise output in contrast to the --shell & sed approaches below.
          #xmllint --help 2>&1 | grep -i 'xpath'



           sed '1d;$d')"
          password="$(echo "cat /config/global/resources/default_setup/connection/password/text()"

          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb



          In case there is just an XML string and the use of a temporary file is to be avoided, file descriptors are the way to go with xmllint (which is given /dev/fd/3 as a file argument here):



          set +H

          xmllint --nocdata --shell /dev/fd/3
          set -H


          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb





          share|improve this answer


















          • 1





            Man page: xmlsoft.org/xmllint.html

            – Jason Pyeron
            Sep 21 '14 at 15:27















          18














          Using bash and xmllint (as given by the tags):



          xmllint --version # xmllint: using libxml version 20703

          # Note: Newer versions of libxml / xmllint have a --xpath option which
          # makes it possible to use xpath expressions directly as arguments.
          # --xpath also enables precise output in contrast to the --shell & sed approaches below.
          #xmllint --help 2>&1 | grep -i 'xpath'



           sed '1d;$d')"
          password="$(echo "cat /config/global/resources/default_setup/connection/password/text()"

          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb



          In case there is just an XML string and the use of a temporary file is to be avoided, file descriptors are the way to go with xmllint (which is given /dev/fd/3 as a file argument here):



          set +H

          xmllint --nocdata --shell /dev/fd/3
          set -H


          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb





          share|improve this answer


















          • 1





            Man page: xmlsoft.org/xmllint.html

            – Jason Pyeron
            Sep 21 '14 at 15:27













          18












          18








          18







          Using bash and xmllint (as given by the tags):



          xmllint --version # xmllint: using libxml version 20703

          # Note: Newer versions of libxml / xmllint have a --xpath option which
          # makes it possible to use xpath expressions directly as arguments.
          # --xpath also enables precise output in contrast to the --shell & sed approaches below.
          #xmllint --help 2>&1 | grep -i 'xpath'



           sed '1d;$d')"
          password="$(echo "cat /config/global/resources/default_setup/connection/password/text()"

          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb



          In case there is just an XML string and the use of a temporary file is to be avoided, file descriptors are the way to go with xmllint (which is given /dev/fd/3 as a file argument here):



          set +H

          xmllint --nocdata --shell /dev/fd/3
          set -H


          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb





          share|improve this answer













          Using bash and xmllint (as given by the tags):



          xmllint --version # xmllint: using libxml version 20703

          # Note: Newer versions of libxml / xmllint have a --xpath option which
          # makes it possible to use xpath expressions directly as arguments.
          # --xpath also enables precise output in contrast to the --shell & sed approaches below.
          #xmllint --help 2>&1 | grep -i 'xpath'



           sed '1d;$d')"
          password="$(echo "cat /config/global/resources/default_setup/connection/password/text()"

          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb



          In case there is just an XML string and the use of a temporary file is to be avoided, file descriptors are the way to go with xmllint (which is given /dev/fd/3 as a file argument here):



          set +H

          xmllint --nocdata --shell /dev/fd/3
          set -H


          # output
          # host: localhost
          # username: root
          # password: pass123
          # dbname: testdb






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jul 18 '13 at 13:39









          paoulpaoul

          1962




          1962







          • 1





            Man page: xmlsoft.org/xmllint.html

            – Jason Pyeron
            Sep 21 '14 at 15:27












          • 1





            Man page: xmlsoft.org/xmllint.html

            – Jason Pyeron
            Sep 21 '14 at 15:27







          1




          1





          Man page: xmlsoft.org/xmllint.html

          – Jason Pyeron
          Sep 21 '14 at 15:27





          Man page: xmlsoft.org/xmllint.html

          – Jason Pyeron
          Sep 21 '14 at 15:27













          6














          Although there are a lot of answers already, I'll chime in with xml2.



          $ xml2 < test.xml
          /config/global/install/date=Tue, 11 Dec 2012 12:31:25 +0000
          /config/global/crypt/key=70e75d7969b900b696785f2f81ecb430
          /config/global/disable_local_modules=false
          /config/global/resources/db/table_prefix
          /config/global/resources/default_setup/connection/host=localhost
          /config/global/resources/default_setup/connection/username=root
          /config/global/resources/default_setup/connection/password=pass123
          /config/global/resources/default_setup/connection/dbname=testdb
          /config/global/resources/default_setup/connection/initStatements=SET NAMES utf8
          /config/global/resources/default_setup/connection/model=mysql4
          /config/global/resources/default_setup/connection/type=pdo_mysql
          /config/global/resources/default_setup/connection/pdoType
          /config/global/resources/default_setup/connection/active=1
          /config/global/session_save=files
          /config/admin/routers/adminhtml/args/frontName=admin


          With a little magic you can even set those as variables directly:



          $ eval $(xml2 < test.xml | tr '/, ' '___' | grep =)
          $ echo $_config_global_resources_default_setup_connection_host
          localhost





          share|improve this answer



























            6














            Although there are a lot of answers already, I'll chime in with xml2.



            $ xml2 < test.xml
            /config/global/install/date=Tue, 11 Dec 2012 12:31:25 +0000
            /config/global/crypt/key=70e75d7969b900b696785f2f81ecb430
            /config/global/disable_local_modules=false
            /config/global/resources/db/table_prefix
            /config/global/resources/default_setup/connection/host=localhost
            /config/global/resources/default_setup/connection/username=root
            /config/global/resources/default_setup/connection/password=pass123
            /config/global/resources/default_setup/connection/dbname=testdb
            /config/global/resources/default_setup/connection/initStatements=SET NAMES utf8
            /config/global/resources/default_setup/connection/model=mysql4
            /config/global/resources/default_setup/connection/type=pdo_mysql
            /config/global/resources/default_setup/connection/pdoType
            /config/global/resources/default_setup/connection/active=1
            /config/global/session_save=files
            /config/admin/routers/adminhtml/args/frontName=admin


            With a little magic you can even set those as variables directly:



            $ eval $(xml2 < test.xml | tr '/, ' '___' | grep =)
            $ echo $_config_global_resources_default_setup_connection_host
            localhost





            share|improve this answer

























              6












              6








              6







              Although there are a lot of answers already, I'll chime in with xml2.



              $ xml2 < test.xml
              /config/global/install/date=Tue, 11 Dec 2012 12:31:25 +0000
              /config/global/crypt/key=70e75d7969b900b696785f2f81ecb430
              /config/global/disable_local_modules=false
              /config/global/resources/db/table_prefix
              /config/global/resources/default_setup/connection/host=localhost
              /config/global/resources/default_setup/connection/username=root
              /config/global/resources/default_setup/connection/password=pass123
              /config/global/resources/default_setup/connection/dbname=testdb
              /config/global/resources/default_setup/connection/initStatements=SET NAMES utf8
              /config/global/resources/default_setup/connection/model=mysql4
              /config/global/resources/default_setup/connection/type=pdo_mysql
              /config/global/resources/default_setup/connection/pdoType
              /config/global/resources/default_setup/connection/active=1
              /config/global/session_save=files
              /config/admin/routers/adminhtml/args/frontName=admin


              With a little magic you can even set those as variables directly:



              $ eval $(xml2 < test.xml | tr '/, ' '___' | grep =)
              $ echo $_config_global_resources_default_setup_connection_host
              localhost





              share|improve this answer













              Although there are a lot of answers already, I'll chime in with xml2.



              $ xml2 < test.xml
              /config/global/install/date=Tue, 11 Dec 2012 12:31:25 +0000
              /config/global/crypt/key=70e75d7969b900b696785f2f81ecb430
              /config/global/disable_local_modules=false
              /config/global/resources/db/table_prefix
              /config/global/resources/default_setup/connection/host=localhost
              /config/global/resources/default_setup/connection/username=root
              /config/global/resources/default_setup/connection/password=pass123
              /config/global/resources/default_setup/connection/dbname=testdb
              /config/global/resources/default_setup/connection/initStatements=SET NAMES utf8
              /config/global/resources/default_setup/connection/model=mysql4
              /config/global/resources/default_setup/connection/type=pdo_mysql
              /config/global/resources/default_setup/connection/pdoType
              /config/global/resources/default_setup/connection/active=1
              /config/global/session_save=files
              /config/admin/routers/adminhtml/args/frontName=admin


              With a little magic you can even set those as variables directly:



              $ eval $(xml2 < test.xml | tr '/, ' '___' | grep =)
              $ echo $_config_global_resources_default_setup_connection_host
              localhost






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jul 18 '13 at 19:27









              bahamatbahamat

              25k15090




              25k15090





















                  3














                  The following works when run against your test data:



                   read -r host; read -r username; read -r password; read -r dbname; 
                  < <(xmlstarlet sel -t -m /config/global/resources/default_setup/connection
                  -v ./host -n
                  -v ./username -n
                  -v ./password -n
                  -v ./dbname -n)


                  This puts the content into variables host, username, password and dbname.






                  share|improve this answer

























                  • xmlstarlet: command not found, so this command is not useful to me :(

                    – MagePsycho
                    Jul 17 '13 at 15:31











                  • @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

                    – Charles Duffy
                    Jul 17 '13 at 15:48












                  • @CharlesDuffy is there a way to get the value may be using regex pattern or else?

                    – MagePsycho
                    Jul 17 '13 at 15:51






                  • 5





                    @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

                    – terdon
                    Jul 17 '13 at 15:57






                  • 1





                    @MagePsycho I was about to post the same link terdon already did. In short: No.

                    – Charles Duffy
                    Jul 17 '13 at 16:05















                  3














                  The following works when run against your test data:



                   read -r host; read -r username; read -r password; read -r dbname; 
                  < <(xmlstarlet sel -t -m /config/global/resources/default_setup/connection
                  -v ./host -n
                  -v ./username -n
                  -v ./password -n
                  -v ./dbname -n)


                  This puts the content into variables host, username, password and dbname.






                  share|improve this answer

























                  • xmlstarlet: command not found, so this command is not useful to me :(

                    – MagePsycho
                    Jul 17 '13 at 15:31











                  • @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

                    – Charles Duffy
                    Jul 17 '13 at 15:48












                  • @CharlesDuffy is there a way to get the value may be using regex pattern or else?

                    – MagePsycho
                    Jul 17 '13 at 15:51






                  • 5





                    @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

                    – terdon
                    Jul 17 '13 at 15:57






                  • 1





                    @MagePsycho I was about to post the same link terdon already did. In short: No.

                    – Charles Duffy
                    Jul 17 '13 at 16:05













                  3












                  3








                  3







                  The following works when run against your test data:



                   read -r host; read -r username; read -r password; read -r dbname; 
                  < <(xmlstarlet sel -t -m /config/global/resources/default_setup/connection
                  -v ./host -n
                  -v ./username -n
                  -v ./password -n
                  -v ./dbname -n)


                  This puts the content into variables host, username, password and dbname.






                  share|improve this answer















                  The following works when run against your test data:



                   read -r host; read -r username; read -r password; read -r dbname; 
                  < <(xmlstarlet sel -t -m /config/global/resources/default_setup/connection
                  -v ./host -n
                  -v ./username -n
                  -v ./password -n
                  -v ./dbname -n)


                  This puts the content into variables host, username, password and dbname.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 17 '13 at 17:01

























                  answered Jul 17 '13 at 15:18









                  Charles DuffyCharles Duffy

                  838514




                  838514












                  • xmlstarlet: command not found, so this command is not useful to me :(

                    – MagePsycho
                    Jul 17 '13 at 15:31











                  • @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

                    – Charles Duffy
                    Jul 17 '13 at 15:48












                  • @CharlesDuffy is there a way to get the value may be using regex pattern or else?

                    – MagePsycho
                    Jul 17 '13 at 15:51






                  • 5





                    @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

                    – terdon
                    Jul 17 '13 at 15:57






                  • 1





                    @MagePsycho I was about to post the same link terdon already did. In short: No.

                    – Charles Duffy
                    Jul 17 '13 at 16:05

















                  • xmlstarlet: command not found, so this command is not useful to me :(

                    – MagePsycho
                    Jul 17 '13 at 15:31











                  • @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

                    – Charles Duffy
                    Jul 17 '13 at 15:48












                  • @CharlesDuffy is there a way to get the value may be using regex pattern or else?

                    – MagePsycho
                    Jul 17 '13 at 15:51






                  • 5





                    @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

                    – terdon
                    Jul 17 '13 at 15:57






                  • 1





                    @MagePsycho I was about to post the same link terdon already did. In short: No.

                    – Charles Duffy
                    Jul 17 '13 at 16:05
















                  xmlstarlet: command not found, so this command is not useful to me :(

                  – MagePsycho
                  Jul 17 '13 at 15:31





                  xmlstarlet: command not found, so this command is not useful to me :(

                  – MagePsycho
                  Jul 17 '13 at 15:31













                  @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

                  – Charles Duffy
                  Jul 17 '13 at 15:48






                  @MagePsycho bash does not have any built-in support for XML parsing. You either need to have a tool that does (xmlstarlet, xsltproc, a modern Python, etc), or you can't parse XML correctly.

                  – Charles Duffy
                  Jul 17 '13 at 15:48














                  @CharlesDuffy is there a way to get the value may be using regex pattern or else?

                  – MagePsycho
                  Jul 17 '13 at 15:51





                  @CharlesDuffy is there a way to get the value may be using regex pattern or else?

                  – MagePsycho
                  Jul 17 '13 at 15:51




                  5




                  5





                  @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

                  – terdon
                  Jul 17 '13 at 15:57





                  @MagePsycho you can just install xmlstarlet. In any case, you should never use regular expressions to parse (X)HTML.

                  – terdon
                  Jul 17 '13 at 15:57




                  1




                  1





                  @MagePsycho I was about to post the same link terdon already did. In short: No.

                  – Charles Duffy
                  Jul 17 '13 at 16:05





                  @MagePsycho I was about to post the same link terdon already did. In short: No.

                  – Charles Duffy
                  Jul 17 '13 at 16:05











                  3














                  A pure bash function, just for the unfortunate case when you are not allowed to install anything appropriate. This may, and probably will, fail on more complicated XML:



                  function xmlpath()

                  local expr="$1//// "
                  local path=()
                  local chunk tag data

                  while IFS='' read -r -d '<' chunk; do
                  IFS='>' read -r tag data <<< "$chunk"

                  case "$tag" in
                  '?'*) ;;
                  '!–-'*) ;;
                  '![CDATA['*) data="$tag:8:$#tag-10" ;;
                  ?*'/') ;;
                  '/'?*) unset path[$#path[@]-1] ;;
                  ?*) path+=("$tag") ;;
                  esac

                  [[ "$path[@]" == "$expr" ]] && echo "$data"
                  done



                  Usage:



                  bash-4.1$ xmlpath 'config/global/resources/default_setup/connection/host' < MagePsycho.xml
                  localhost


                  Known issues:



                  • slow

                  • searches only by tag names

                  • no character entity decoding





                  share|improve this answer



























                    3














                    A pure bash function, just for the unfortunate case when you are not allowed to install anything appropriate. This may, and probably will, fail on more complicated XML:



                    function xmlpath()

                    local expr="$1//// "
                    local path=()
                    local chunk tag data

                    while IFS='' read -r -d '<' chunk; do
                    IFS='>' read -r tag data <<< "$chunk"

                    case "$tag" in
                    '?'*) ;;
                    '!–-'*) ;;
                    '![CDATA['*) data="$tag:8:$#tag-10" ;;
                    ?*'/') ;;
                    '/'?*) unset path[$#path[@]-1] ;;
                    ?*) path+=("$tag") ;;
                    esac

                    [[ "$path[@]" == "$expr" ]] && echo "$data"
                    done



                    Usage:



                    bash-4.1$ xmlpath 'config/global/resources/default_setup/connection/host' < MagePsycho.xml
                    localhost


                    Known issues:



                    • slow

                    • searches only by tag names

                    • no character entity decoding





                    share|improve this answer

























                      3












                      3








                      3







                      A pure bash function, just for the unfortunate case when you are not allowed to install anything appropriate. This may, and probably will, fail on more complicated XML:



                      function xmlpath()

                      local expr="$1//// "
                      local path=()
                      local chunk tag data

                      while IFS='' read -r -d '<' chunk; do
                      IFS='>' read -r tag data <<< "$chunk"

                      case "$tag" in
                      '?'*) ;;
                      '!–-'*) ;;
                      '![CDATA['*) data="$tag:8:$#tag-10" ;;
                      ?*'/') ;;
                      '/'?*) unset path[$#path[@]-1] ;;
                      ?*) path+=("$tag") ;;
                      esac

                      [[ "$path[@]" == "$expr" ]] && echo "$data"
                      done



                      Usage:



                      bash-4.1$ xmlpath 'config/global/resources/default_setup/connection/host' < MagePsycho.xml
                      localhost


                      Known issues:



                      • slow

                      • searches only by tag names

                      • no character entity decoding





                      share|improve this answer













                      A pure bash function, just for the unfortunate case when you are not allowed to install anything appropriate. This may, and probably will, fail on more complicated XML:



                      function xmlpath()

                      local expr="$1//// "
                      local path=()
                      local chunk tag data

                      while IFS='' read -r -d '<' chunk; do
                      IFS='>' read -r tag data <<< "$chunk"

                      case "$tag" in
                      '?'*) ;;
                      '!–-'*) ;;
                      '![CDATA['*) data="$tag:8:$#tag-10" ;;
                      ?*'/') ;;
                      '/'?*) unset path[$#path[@]-1] ;;
                      ?*) path+=("$tag") ;;
                      esac

                      [[ "$path[@]" == "$expr" ]] && echo "$data"
                      done



                      Usage:



                      bash-4.1$ xmlpath 'config/global/resources/default_setup/connection/host' < MagePsycho.xml
                      localhost


                      Known issues:



                      • slow

                      • searches only by tag names

                      • no character entity decoding






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jul 18 '13 at 11:12









                      manatworkmanatwork

                      22.3k38386




                      22.3k38386





















                          0














                          You can make use of php command line interface coding in bash scripts to handle several complex scripts that actually span over multiple lines of coding. First, try to make your solution using PHP scripts, and then later on pass the parameters using CLI mode. Thus, you can get control over superb usages of XML parsers.



                          The environment seems that you can use PHP in client mode via ssh/shell access.



                          php -f yourxmlparser.php


                          Now, do all the things within your php file. Make use of command line parameters it can take.



                          You can even assign that return values to Shell environment to continue rest of your shell scripts.



                          And the other way is to use |grep option to match your required value within the xml file, if you are pretty sure of the structure of your xml file that does not change over time.






                          share|improve this answer





























                            0














                            You can make use of php command line interface coding in bash scripts to handle several complex scripts that actually span over multiple lines of coding. First, try to make your solution using PHP scripts, and then later on pass the parameters using CLI mode. Thus, you can get control over superb usages of XML parsers.



                            The environment seems that you can use PHP in client mode via ssh/shell access.



                            php -f yourxmlparser.php


                            Now, do all the things within your php file. Make use of command line parameters it can take.



                            You can even assign that return values to Shell environment to continue rest of your shell scripts.



                            And the other way is to use |grep option to match your required value within the xml file, if you are pretty sure of the structure of your xml file that does not change over time.






                            share|improve this answer



























                              0












                              0








                              0







                              You can make use of php command line interface coding in bash scripts to handle several complex scripts that actually span over multiple lines of coding. First, try to make your solution using PHP scripts, and then later on pass the parameters using CLI mode. Thus, you can get control over superb usages of XML parsers.



                              The environment seems that you can use PHP in client mode via ssh/shell access.



                              php -f yourxmlparser.php


                              Now, do all the things within your php file. Make use of command line parameters it can take.



                              You can even assign that return values to Shell environment to continue rest of your shell scripts.



                              And the other way is to use |grep option to match your required value within the xml file, if you are pretty sure of the structure of your xml file that does not change over time.






                              share|improve this answer















                              You can make use of php command line interface coding in bash scripts to handle several complex scripts that actually span over multiple lines of coding. First, try to make your solution using PHP scripts, and then later on pass the parameters using CLI mode. Thus, you can get control over superb usages of XML parsers.



                              The environment seems that you can use PHP in client mode via ssh/shell access.



                              php -f yourxmlparser.php


                              Now, do all the things within your php file. Make use of command line parameters it can take.



                              You can even assign that return values to Shell environment to continue rest of your shell scripts.



                              And the other way is to use |grep option to match your required value within the xml file, if you are pretty sure of the structure of your xml file that does not change over time.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jul 18 '13 at 10:33

























                              answered Jul 18 '13 at 10:25









                              Bimal PoudelBimal Poudel

                              1145




                              1145





















                                  0














                                  Using xmllint and the --xpath option, it is very easy. You can simply do this:



                                  XML_FILE=/path/to/file.xml

                                  HOST=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/host)' $XML_FILE
                                  USERNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/username)' $XML_FILE
                                  PASSWORD=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/password)' $XML_FILE
                                  DBNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/dbname)' $XML_FILE


                                  If you need to get to an element's attribute, that's also easy using XPath. Imagine you have the file:



                                  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                                  <addon id="screensaver.turnoff"
                                  name="Turn Off"
                                  version="0.10.0"
                                  provider-name="Dag Wieërs">
                                  ..snip..
                                  </addon>


                                  The needed shell statements would be:



                                  VERSION=$(xmllint --xpath 'string(/addon/@version)' $ADDON_XML)
                                  AUTHOR=$(xmllint --xpath 'string(/addon/@provider-name)' $ADDON_XML)





                                  share|improve this answer



























                                    0














                                    Using xmllint and the --xpath option, it is very easy. You can simply do this:



                                    XML_FILE=/path/to/file.xml

                                    HOST=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/host)' $XML_FILE
                                    USERNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/username)' $XML_FILE
                                    PASSWORD=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/password)' $XML_FILE
                                    DBNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/dbname)' $XML_FILE


                                    If you need to get to an element's attribute, that's also easy using XPath. Imagine you have the file:



                                    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                                    <addon id="screensaver.turnoff"
                                    name="Turn Off"
                                    version="0.10.0"
                                    provider-name="Dag Wieërs">
                                    ..snip..
                                    </addon>


                                    The needed shell statements would be:



                                    VERSION=$(xmllint --xpath 'string(/addon/@version)' $ADDON_XML)
                                    AUTHOR=$(xmllint --xpath 'string(/addon/@provider-name)' $ADDON_XML)





                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      Using xmllint and the --xpath option, it is very easy. You can simply do this:



                                      XML_FILE=/path/to/file.xml

                                      HOST=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/host)' $XML_FILE
                                      USERNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/username)' $XML_FILE
                                      PASSWORD=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/password)' $XML_FILE
                                      DBNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/dbname)' $XML_FILE


                                      If you need to get to an element's attribute, that's also easy using XPath. Imagine you have the file:



                                      <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                                      <addon id="screensaver.turnoff"
                                      name="Turn Off"
                                      version="0.10.0"
                                      provider-name="Dag Wieërs">
                                      ..snip..
                                      </addon>


                                      The needed shell statements would be:



                                      VERSION=$(xmllint --xpath 'string(/addon/@version)' $ADDON_XML)
                                      AUTHOR=$(xmllint --xpath 'string(/addon/@provider-name)' $ADDON_XML)





                                      share|improve this answer













                                      Using xmllint and the --xpath option, it is very easy. You can simply do this:



                                      XML_FILE=/path/to/file.xml

                                      HOST=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/host)' $XML_FILE
                                      USERNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/username)' $XML_FILE
                                      PASSWORD=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/password)' $XML_FILE
                                      DBNAME=$(xmllint --xpath 'string(/config/global/resources/default_setup/connection/dbname)' $XML_FILE


                                      If you need to get to an element's attribute, that's also easy using XPath. Imagine you have the file:



                                      <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                                      <addon id="screensaver.turnoff"
                                      name="Turn Off"
                                      version="0.10.0"
                                      provider-name="Dag Wieërs">
                                      ..snip..
                                      </addon>


                                      The needed shell statements would be:



                                      VERSION=$(xmllint --xpath 'string(/addon/@version)' $ADDON_XML)
                                      AUTHOR=$(xmllint --xpath 'string(/addon/@provider-name)' $ADDON_XML)






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 14 at 23:13









                                      Dag WieersDag Wieers

                                      19615




                                      19615



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f83385%2fparse-xml-to-get-node-value-in-bash-script%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown






                                          Popular posts from this blog

                                          How to check contact read email or not when send email to Individual?

                                          Bahrain

                                          Postfix configuration issue with fips on centos 7; mailgun relay