XPath for libvirt external snapshop path

The following xmllint XPath query will pull out the name of the backing file for a VM named fedora-server-36 and an external snapshot named fedora-36-post-install,

virsh snapshot-dumpxml fedora-server-36 fedora-server-36-post-install | xmllint --xpath "string(//domainsnapshot/disks/disk[@snapshot='external']/source/@file)" -

The string function extracts the attribute value.

This value can be used in the process of using or deleting the snapshot.

Parsing libvirt xmldump using xpath

In a recent article, I saw yet another example of using grep to pull information out of xml, and then to manually look for a field. However, XML is structured, and with XPath, we can pull out exactly what we need.

virsh dumpxml fedora-server-36 | xmllint --xpath "//domain/devices/disk[@device='disk']"  -

That will produce output like this:

<disk type="file" device="disk">
      <driver name="qemu" type="qcow2" discard="unmap"/>
      <source file="/var/lib/libvirt/images/fedora-server-36.qcow2"/>
      <target dev="vda" bus="virtio"/>
      <address type="pci" domain="0x0000" bus="0x05" slot="0x00" function="0x0"/>
</disk>

Note that I did more in my XPath than required by the original article. I wanted to show an example of querying based on an attribute inside the selected node.

Update: Here is an example for what is done later in the article: pull the path out of the pool xml.

virsh pool-dumpxml default |  xmllint --xpath "//pool/target/path/text()"  -
/var/lib/libvirt/images