Hakim OUBOUALI
Hakim OUBOUALI

Reputation: 13

how do you parse from XML using yq?

Hi I would like to parse the servers names using yq the problem is that I have to specify the index of each server every time i wounder if the is a method to get the servers names without specifying the index using yq or any other methods.

╭─hakim🐺imap in ~/notes on main ✘ (origin/main)
╰$ cat /home/hakim/Oracle/Middleware/Oracle_Home/user_projects/domains/base_domain/original/config.xml | yq -p=xml .domain.server
- name: AdminServer
  ssl:
    name: AdminServer
    listen-port: "7002"
  listen-address:
- name: Server_1
  machine: Machine_1
  listen-port: "7003"
  cluster: Cluster_1
  listen-address:
  jta-migratable-target:
    user-preferred-server: Server_1
    cluster: Cluster_1
- name: Server_2
  machine: Machine_1
  listen-port: "7004"
  cluster: Cluster_1
  listen-address:
  jta-migratable-target:
    user-preferred-server: Server_2
    cluster: Cluster_1
- name: Server_3
  machine: Machine_1
  listen-port: "7005"
  cluster: Cluster_1
  listen-address:
  jta-migratable-target:
    user-preferred-server: Server_3
    cluster: Cluster_1

Upvotes: 1

Views: 1913

Answers (1)

LMC
LMC

Reputation: 12662

Pass a query to request the info. In this case '.domain.server[] | .name' will get server names

# multiple servers
yq -o 'y' '.domain.server[] | .name' config.xml
# single server
yq -o 'y' '.domain.server | .name' config.xml

For some version around v4.35.x of yq below command would throw a warning

12:14:03 initCommand [WARN] yq default output is now 'auto' (based on the filename extension). Normally yq would output 'xml', but for backwards compatibility 'yaml' has been set. Please use -oy to specify yaml, or drop the -p flag.

yq -p xml '.domain.server[] | .name' test.xml

Result

AdminServer
edys-web

From yq help

-p, --input-format string
-o, --output-format string [auto|a|yaml|y|json|j|props|p|xml|x|tsv|t|csv|c] output format type. (default "auto")

yq -oy ... is a bit confusing to me as in some command it could mean cmd -o -y, so

yq -o 'y' ...
yq -o 'yaml' ...
yq --output-format 'y' ...

:-)

Upvotes: 4

Related Questions