5

I have an xml file

<?xml version="1.0"?>
<preferences>
    <!--General options-->
    <options>
            <dbHost>localhost</dbHost>
            <dbUser>bwserver</dbUser>
            <dbPass>bwserver</dbPass>
            <dbPort>3306</dbPort>

How can i update the value dbUser?

When I type

xmlstarlet edit --update '/preferences/options/dbUser/'  --value 123 preferences.xml

nothing happens. I only see the file contents in terminal. The xml file was not touched.

mles
  • 4,534
  • 10
  • 54
  • 94
user2114620
  • 61
  • 2
  • 4

1 Answers1

9

You have two faults:

  1. Your XPath expression is invalid. Drop the trailing slash so it becomes /preferences/options/dbUser
  2. By default xmlstarlet does not change the input file, instead it outputs the result in stdout. You can either replace the original file with the xmlstarlet output by redirecting the output to your input file (or to any other file) xmlstarlet edit --update '/preferences/options/dbUser' --value 123 preferences.xml > preferences.xml or you can use global option --inplace which replaces the input file with the output (instead of printing it to stdin). The command is xmlstarlet edit --inplace --update '/preferences/options/dbUser' --value 123 preferences.xml

Type xmlstarlet edit --help for more info

jasso
  • 13,736
  • 2
  • 36
  • 50
  • 1
    redirecting into the same file is an error in shell scripting. You can get away with it for small files, but the `> preferences.xml` by itself will create a new file. (My xmlstarlet doesn't have an --inplace global option for edit), so the safest path is `xmlstarlet .... file.xml > tmp_file.xml && /bin/mv tmp_file.xml file.xml` . (For the times when there are new requirements, etc needed in processing of original file), I prefer to keep my original and have the following steps use the new file, but of course this doubles space usage and requires extra cleanup at some point. Good luck to all. – shellter Dec 18 '17 at 18:12