XML a YAML
Converte XML in formato YAML
Input XML
Output YAML
Cos'è la conversione da XML a YAML?
La conversione da XML a YAML trasforma i dati da Extensible Markup Language (XML) a YAML Ain't Markup Language (YAML). XML usa tag con parentesi angolari e attributi per descrivere dati gerarchici, mentre YAML rappresenta le stesse strutture tramite indentazione e coppie chiave-valore in testo semplice. Convertire XML in YAML online è un'operazione comune quando si migra la configurazione da sistemi basati su XML — come Java Spring, Maven o .NET — a piattaforme che preferiscono YAML, come Kubernetes, Ansible, GitHub Actions e Docker Compose.
I due formati differiscono nel modello dei dati. XML tratta tutto come testo di default e si affida a definizioni di schema (XSD, DTD) per l'applicazione dei tipi. YAML ha tipi nativi: stringhe, interi, float, booleani, null, sequenze (array) e mapping (oggetti). Durante la conversione, valori come "true", "5432" e "3.14" possono essere interpretati come tipi nativi YAML invece di rimanere stringhe. Un convertitore accurato racchiude questi valori tra virgolette per preservare la rappresentazione testuale originale della sorgente XML.
XML supporta anche costrutti privi di equivalente YAML: attributi, namespace, istruzioni di elaborazione, sezioni CDATA e commenti. La conversione deve scegliere una convenzione per rappresentare gli attributi (comunemente chiavi con prefisso underscore come _attr) e decidere se ignorare o appiattire il resto. Comprendere questi compromessi prima di convertire aiuta a scegliere lo strumento giusto, configurarlo correttamente e verificare che l'output YAML corrisponda all'intento originale dell'XML.
<server>
<host>db.example.com</host>
<port>5432</port>
<credentials admin="true">
<username>deploy</username>
<password>s3cret</password>
</credentials>
<options>
<option>ssl=true</option>
<option>timeout=30</option>
</options>
</server>server:
host: db.example.com
port: "5432"
credentials:
_admin: "true"
username: deploy
password: s3cret
options:
option:
- ssl=true
- timeout=30Perché usare un convertitore XML in YAML online?
Scrivere uno script di conversione manuale richiede di gestire la mappatura degli attributi, il rilevamento degli array per gli elementi ripetuti e i casi limite della coercizione di tipo YAML. Un convertitore basato su browser gestisce tutto in un unico passaggio, permettendo di ispezionare l'output YAML e copiarlo direttamente nei file di configurazione.
Casi d'uso della conversione XML in YAML
Riferimento alla mappatura XML in YAML
XML e YAML hanno modelli di dati diversi. La tabella seguente mostra come ogni costrutto XML si mappa al proprio equivalente YAML. Gli attributi vengono tipicamente convertiti in chiavi con prefisso underscore, e gli elementi ripetuti diventano sequenze YAML. Alcuni costrutti come commenti e istruzioni di elaborazione non hanno rappresentazione YAML e vengono scartati durante la conversione.
| Costrutto XML | Esempio XML | Equivalente YAML |
|---|---|---|
| Element | <name>text</name> | name: text |
| Nested elements | <a><b>1</b></a> | a:\n b: "1" |
| Attributes | <el attr="v"/> | el:\n _attr: v |
| Text + attributes | <el a="1">text</el> | el:\n _a: "1"\n _text: text |
| Repeated elements | <r><i>1</i><i>2</i></r> | r:\n i:\n - "1"\n - "2" |
| Empty element | <el/> | el: "" |
| CDATA | <![CDATA[raw]]> | Treated as plain text |
| Comments | <!-- note --> | Discarded (no YAML equivalent) |
| Namespaces | xmlns:ns="uri" | Prefix preserved or stripped |
| Boolean-like text | <flag>true</flag> | flag: "true" (quoted to stay string) |
XML vs YAML: differenze nel modello dei dati
Convertire tra XML e YAML non è un semplice cambio di sintassi. I due formati hanno differenze strutturali fondamentali che influenzano la rappresentazione dei dati dopo la conversione.
Esempi di codice
Di seguito trovi esempi funzionanti per convertire XML in YAML in JavaScript, Python, Go e da riga di comando. Ogni esempio gestisce elementi annidati, attributi e tag fratelli ripetuti.
import { parseStringPromise } from 'xml2js'
import YAML from 'yaml'
const xml = `
<config>
<database host="localhost" port="5432">
<name>mydb</name>
</database>
<features>
<feature>auth</feature>
<feature>logging</feature>
</features>
</config>`
const obj = await parseStringPromise(xml, { explicitArray: false })
console.log(YAML.stringify(obj))
// → config:
// → database:
// → $:
// → host: localhost
// → port: "5432"
// → name: mydb
// → features:
// → feature:
// → - auth
// → - loggingimport xmltodict
import yaml
xml = """
<server>
<host>db.example.com</host>
<port>5432</port>
<replicas>
<replica>node-1</replica>
<replica>node-2</replica>
</replicas>
</server>
"""
# Step 1: XML → Python dict
data = xmltodict.parse(xml)
# Step 2: Python dict → YAML
print(yaml.dump(data, default_flow_style=False))
# → server:
# → host: db.example.com
# → port: '5432'
# → replicas:
# → replica:
# → - node-1
# → - node-2
# With the standard library only (no xmltodict)
import xml.etree.ElementTree as ET
def elem_to_dict(elem):
d = {}
if elem.attrib:
d.update({f"_{k}": v for k, v in elem.attrib.items()})
for child in elem:
val = elem_to_dict(child)
if child.tag in d:
if not isinstance(d[child.tag], list):
d[child.tag] = [d[child.tag]]
d[child.tag].append(val)
else:
d[child.tag] = val
if elem.text and elem.text.strip():
text = elem.text.strip()
return text if not d else {**d, "_text": text}
return d
root = ET.fromstring(xml)
print(yaml.dump({root.tag: elem_to_dict(root)}, default_flow_style=False))# xq is part of the yq package (pip install yq) # It parses XML via xq and outputs JSON, then pipe to yq for YAML echo '<config><host>localhost</host><port>8080</port></config>' | xq . | yq -y . # → config: # → host: localhost # → port: "8080" # Using xmlstarlet + yq (Go version: https://github.com/mikefarah/yq) xmlstarlet sel -t -c '/' input.xml | yq -p=xml -o=yaml # Reads XML from file and outputs YAML directly
package main
import (
"encoding/xml"
"fmt"
"strings"
"gopkg.in/yaml.v3"
)
type Server struct {
XMLName xml.Name `xml:"server"`
Host string `xml:"host" yaml:"host"`
Port int `xml:"port" yaml:"port"`
Options []string `xml:"options>option" yaml:"options"`
}
func main() {
data := `<server>
<host>db.example.com</host>
<port>5432</port>
<options><option>ssl=true</option><option>timeout=30</option></options>
</server>`
var srv Server
xml.NewDecoder(strings.NewReader(data)).Decode(&srv)
out, _ := yaml.Marshal(srv)
fmt.Println(string(out))
// → host: db.example.com
// → port: 5432
// → options:
// → - ssl=true
// → - timeout=30
}