Search code examples
xmlawkxml-parsinggrepxmlstarlet

How to validate xml tags using xmlstarlet?


I have an xml file: config.xml with following tags in it:

 <roleMap type="globalRoles">
  <role name="ABC Employee" pattern=".*">
     <assignedSIDs>
      <sid>abc</sid>
      <sid>cde</sid>
      <sid>efg</sid>
    </assignedSIDs>
  </role>
 </roleMap>

<roleMap type="projectRoles">
   <role name="Proj1" pattern="Proj1.*">
    <permissions/>
    <assignedSIDs>
      <sid>abc</sid>
      <sid>jkl</sid>
     </assignedSIDs>
  </role>

  <role name="Proj2" pattern="Proj2.*">
    <permissions/>
    <assignedSIDs>
      <sid>hij</sid>
      <sid>cde</sid>          
    </assignedSIDs>
  </role>


  <role name="Proj3" pattern="Proj3.*">
    <permissions/>
     <assignedSIDs>
      <sid>zxc</sid>
      <sid>efg</sid>
    </assignedSIDs>
  </role>
</roleMap>

It contains two roleMap tags type: globalRoles and projectRoles.

Till now,I have been able to add user in globalRoles and projectRoles using following shell script:

read -p 'Enter UserName and projectName  :' user projectName
echo -e "user name :$user       project name :$projectName"

xmlstarlet ed -P -S -s "/hudson/authorizationStrategy/roleMap
[@type='globalRoles']/role[@name='ABC Employee']/assignedSIDs"
 -t elem -n sid -v $user -s "/hudson/authorizationStrategy/roleMap
 [@type='projectRoles']/role[@name='$projectName']/assignedSIDs" -t elem 
 -n sid -v $user  config.xml >me1.xml

mv config.xml config_old.xml
mv me1.xml config.xml

What I need is to include some condition in the script, which would help me:
1)Validate xml file ( whether all tags are closed or not.)
2)Find whether the $user is already present in global roles or not. (if user is already present in global roles, script should not add the user and give warning " user already exist in global role").
3)Find whether user is already present in projectRoles of specific project.( if user is present in specific project, script must give warning " user is already present in that specific project").

I am not sure which command can be used to validate tags in xml file. ( I am thinking of using grep command or awk ).


Solution

  • First of all thanks for everyone's input. Firstly i validated the xml file using following command:

    xmlstarlet val -w config.xml

    Then, I used grep command in if.. else.. fi conditional loop to validate user present in xml file.

    if(echo $user | grep -o -q "$user" config.xml).... then... else... fi.