3

In shell script, I have an xml file as p.xml, as follows and I want to parse it and get values in two arrays. I am trying to use xmllint, but could not get desired data.

    <?xml version="1.0" encoding="UTF-8"?>
    <Share_Collection>
      <Share id="data/Backup" resource-id="data/Backup" resource-type="SimpleShare" share-name="Backup" protocols="cifs,afp"/>
      <Share id="data/Documents" resource-id="data/Documents" resource-type="SimpleShare" share-name="Documents" protocols="cifs,afp"/>
      <Share id="data/Music" resource-id="data/Music" resource-type="SimpleShare" share-name="Music" protocols="cifs,afp"/>
      <Share id="data/OwnCloud" resource-id="data/OwnCloud" resource-type="SimpleShare" share-name="OwnCloud" protocols="cifs,afp"/>
      <Share id="data/Pictures" resource-id="data/Pictures" resource-type="SimpleShare" share-name="Pictures" protocols="cifs,afp"/>
      <Share id="data/Videos" resource-id="data/Videos" resource-type="SimpleShare" share-name="Videos" protocols="cifs,afp"/>
    </Share_Collection>

I want to get an array all share ids and one array containing share-names. So two array would be like

share-ids-array = ["data/Backup", "data/Documents", "data/Music", "data/OwnCloud", "data/Pictures", "data/Videos"]     

share-names-array = ["Backup", "Documents", "Music", "OwnCloud", "Pictures", "Videos"]

I started as follows:

xmllint --xpath '//Share/@id' p.xml 
xmllint --xpath '//Share/@share-name' p.xml 

that gives me

id="data/Backup" 
id="data/Documents" id="data/Music" id="data/OwnCloud" id="data/Pictures" id="data/Videos" 

Any help to build those two arrays will be appreciated.

1 Answer 1

6

Here is one solution with grep (and tr)...sed or awk are other alternatives. By the way, you cannot use hyphens in variable names in bash.

share_ids=($( xmllint --xpath '//Share/@id' p.xml | grep -Po '".*?"' | tr -d \" ))
share_names=($( xmllint --xpath '//Share/@share-name' p.xml | grep -Po '".*?"' | tr -d \" ))

Example:

$ echo ${share_names[@]}
Backup Documents Music OwnCloud Pictures Videos

Using xmlstarlet is probably better, though:

share_names=($( xmlstarlet sel -T -t -m '//Share/@share-name' -v '.' -n p.xml ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.