Shellscript Read XML attribute value

后端 未结 3 994
刺人心
刺人心 2021-01-05 23:08

We want to read XML attributes from an XML file. Example of file content is as below:


  
  <         


        
相关标签:
3条回答
  • 2021-01-05 23:14

    sed -n '/<property name="abc"/s/.*value="\(.*\)"[^\n]*/\1/p' file

    Creates a hold pattern for the value then matches everything except for the newline to avoid printing the newline, it expects the value double quoted as per your example data.

    E.g. 
    <properties>
      <property name="abc" value="15"/>
      <property name="xyz" value="26"/>
    </properties>
    
    Output:
    15
    

    (Prior to edit: sed '/<property name="abc"/s/.*value="\(.*\)"[^\n]*/\1/' file)

    0 讨论(0)
  • 2021-01-05 23:18

    You can use a proper XML parser like xmllint. If your version supports xpath, it will be very easy to grab specific values. If it doesn't support xpath, then you can use --shell option like so:

    $ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml
    / >  -------
     value="15"
    / > 
    

    You can then use awk or sed to format and extract desired field from output.

    $ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxmlfile | awk -F'[="]' '!/>/{print $(NF-1)}'
    15
    

    You can use command substitution to capture the output in a variable by saying:

    $ myvar=$(echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml | awk -F'[="]' '!/>/{print $(NF-1)}')
    $ echo "$myvar"
    15
    

    Using anything else other than a xmlparser is prone to errors and will break easy.

    0 讨论(0)
  • 2021-01-05 23:18

    quick and dirty

    sed -n '/<Properties>/,\|</properties>| {
       s/ *<property name="xyz" value="\([^"]*\)"\/>/\1/p
       }'
    

    no xml check and based on your sample so assume same structure (one property name per line, ...)

    posix version (--posix for GNU sed)

    0 讨论(0)
提交回复
热议问题