Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

XML Processing with Shell Scripts

Introduction to XML Processing

XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. This tutorial explores how to process XML data using shell scripts.

Parsing XML Files

Shell scripts can parse XML files using tools like xmlstarlet, which provides command-line XML processing utilities.

Basic XML Parsing


#!/bin/bash

# Parse and display XML data from a file
FILE="data.xml"

xmlstarlet sel -t -c "/" "$FILE"
                

This script parses an XML file and outputs its contents.

Extracting Specific Elements

Extracting specific elements from XML files is a common task in XML processing.

Extracting a Single Element


#!/bin/bash

# Extract a specific XML element from a file
FILE="data.xml"
ELEMENT="//bookstore/book[1]/title"

xmlstarlet sel -t -v "$ELEMENT" "$FILE"
                

This script extracts and prints the value of the title element of the first book in an XML file.

Extracting Multiple Elements


#!/bin/bash

# Extract multiple XML elements from a file
FILE="data.xml"
ELEMENTS="//bookstore/book/title | //bookstore/book/price"

xmlstarlet sel -t -m "$ELEMENTS" -v . -n "$FILE"
                

This script extracts and prints the values of the title and price elements from all book elements in an XML file.

Manipulating XML Data

Shell scripts can manipulate XML data by modifying existing elements, adding new elements, or deleting elements.

Modifying XML Elements


#!/bin/bash

# Modify an XML element in a file
FILE="data.xml"
ELEMENT="//bookstore/book[1]/price"
NEW_VALUE="19.99"

xmlstarlet ed -u "$ELEMENT" -v "$NEW_VALUE" "$FILE"
                

This script updates the value of the price element of the first book in an XML file.

Adding New Elements


#!/bin/bash

# Add a new XML element to a file
FILE="data.xml"
NEW_ELEMENT="New Book24.99"

xmlstarlet ed -s "//bookstore" -t elem -n book -v "" -i "//bookstore/book[last()]" -t "elem" -n "title" -v "New Book" -s "//bookstore/book[last()]" -t "elem" -n "price" -v "24.99" "$FILE"
                

This script adds a new book element with title and price sub-elements to an XML file.

Deleting Elements


#!/bin/bash

# Delete an XML element from a file
FILE="data.xml"
ELEMENT="//bookstore/book[1]/title"

xmlstarlet ed -d "$ELEMENT" "$FILE"
                

This script deletes the title element of the first book in an XML file.

Conclusion

XML processing with shell scripts allows for the automation and manipulation of structured data in XML format. By using tools like xmlstarlet effectively, you can parse, extract, modify, and manipulate XML data to suit your needs.