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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.