Search code examples
regexbashshellxmllint

How to find properties containing matching certain pattern using xmllint


I am trying to extract a value in a shell script using xmllint, I was able to find and extract values by matching complete key strings. The problem is for some values I just know what the key starts with. For example: let a part of xml be:

<property>
    <name>foo.bar.random_part_of_name</name>
    <value> SOME_VALUE</value>
 </property>

I want to extract this entire segment as write it to an output file.

So far, I have been able to match complete segments with

if (xmllint --xpath '//property[name/text()="foo.bar"]/value/text()' "$INPUT_FILE"); then
  value=$(xmllint --xpath '//property[name/text()="foo.bar"]/value/text()' "$INPUT_FILE")
  echo "<property><name>foo.bar</name><value>$value</value></property>">> $OUTPUT_FILE
fi

Thanks in advance


Solution

  • Xpath 1.0 offers start-with(node, pattern) function to do what you want

    name="foo.bar"
    value=$(xmllint --xpath "//property[starts-with(name,'$name')]/value/text()" test.xml)
    if [ -n "$value" ]; then
      echo "<property><name>$name</name><value>$value</value></property>"
    fi
    

    Result:

    <property><name>foo.bar</name><value> SOME_VALUE</value></property>