XML to YAML

Convert XML to YAML format

Try an example

XML Input

YAML Output

Runs locally · Safe to paste secrets
YAML will appear here…

What is XML to YAML Conversion?

XML to YAML conversion transforms data from Extensible Markup Language (XML) into YAML Ain't Markup Language (YAML). XML uses angle-bracket tags with attributes to describe hierarchical data, while YAML represents the same structures through indentation and plain-text key-value pairs. Converting XML to YAML online is a common task when migrating configuration from XML-heavy systems like Java Spring, Maven, or .NET to platforms that prefer YAML, such as Kubernetes, Ansible, GitHub Actions, and Docker Compose.

The two formats differ in their data models. XML treats everything as text by default and relies on schema definitions (XSD, DTD) for type enforcement. YAML has native types: strings, integers, floats, booleans, nulls, sequences (arrays), and mappings (objects). During conversion, values like "true", "5432", and "3.14" can be interpreted as YAML native types instead of remaining strings. A careful converter quotes these values to preserve the original text representation from the XML source.

XML also supports constructs that have no YAML counterpart: attributes, namespaces, processing instructions, CDATA sections, and comments. The conversion must choose a convention for representing attributes (commonly underscore-prefixed keys like _attr) and decide whether to discard or flatten the rest. Understanding these trade-offs before converting helps you pick the right tool, configure it correctly, and verify that the YAML output matches the original XML intent.

XML input
<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>
YAML output
server:
  host: db.example.com
  port: "5432"
  credentials:
    _admin: "true"
    username: deploy
    password: s3cret
  options:
    option:
      - ssl=true
      - timeout=30

Why Use an Online XML to YAML Converter?

Writing a conversion script by hand means dealing with attribute mapping, array detection for repeated elements, and YAML type-coercion edge cases. A browser-based converter handles all of that in one step, letting you inspect the YAML output and copy it directly into your config files.

Instant conversion
Paste your XML and get YAML output in milliseconds. No library installation, no build step, no script to maintain.
🔒
Privacy-first processing
The conversion runs entirely in your browser using JavaScript. Your XML data stays on your machine and is never sent to a server.
🔀
Handles attributes and arrays
XML attributes are mapped to prefixed keys. Repeated sibling elements are grouped into YAML sequences automatically, preserving list structures.
📋
No account required
Open the page, paste XML, copy the YAML result. No sign-up, no API key, no rate limits or usage caps.

XML to YAML Use Cases

Frontend development
Convert XML configuration snippets from legacy build tools (Ant, Maven) into YAML for modern CI pipelines like GitHub Actions or GitLab CI that expect YAML config files.
Backend engineering
Migrate Spring XML bean definitions to Spring Boot's application.yml format, or convert .NET app.config sections into YAML for container deployments.
DevOps and infrastructure
Transform XML-based deployment descriptors (Tomcat server.xml, IIS web.config) into YAML equivalents for Kubernetes manifests, Helm charts, or Ansible playbooks.
QA and testing
Convert XML test fixtures or JUnit configuration into YAML for test frameworks that support YAML data sources, such as pytest with YAML fixtures or Robot Framework.
Data engineering
Transform XML data exports from enterprise systems (SAP, Oracle) into YAML for ingestion by ETL tools like dbt or Airflow that use YAML-based configuration and schemas.
Learning and documentation
Students and technical writers can paste XML samples to see how elements, attributes, and nesting translate to YAML indentation, sequences, and mappings.

XML to YAML Mapping Reference

XML and YAML have different data models. The table below shows how each XML construct maps to a YAML equivalent. Attributes are typically converted to underscore-prefixed keys, and repeated elements become YAML sequences. Some constructs like comments and processing instructions have no YAML representation and are discarded during conversion.

XML ConstructXML ExampleYAML Equivalent
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)
Namespacesxmlns:ns="uri"Prefix preserved or stripped
Boolean-like text<flag>true</flag>flag: "true" (quoted to stay string)

XML vs YAML: Data Model Differences

Converting between XML and YAML is not a simple syntax swap. The formats have fundamental structural differences that affect how data is represented after conversion.

Type system
XML stores all values as text strings. YAML has native booleans, integers, floats, and nulls. During conversion, a value like "true" or "3306" may be reinterpreted as a YAML boolean or integer unless the converter quotes it. Always verify type-sensitive values in the output.
Attributes vs keys
XML elements can carry attributes alongside child elements and text content. YAML has only key-value mappings. Attributes must be converted to regular keys, typically with a prefix like _ or @ to distinguish them from child elements.
Order and duplicates
XML preserves document order and allows sibling elements with the same tag name. YAML mappings are unordered by spec (though most parsers preserve insertion order), and duplicate keys are forbidden in YAML 1.2. Repeated XML elements must become a YAML sequence.

Code Examples

Below are working examples for converting XML to YAML in JavaScript, Python, Go, and the command line. Each example handles nested elements, attributes, and repeated sibling tags.

JavaScript (Node.js)
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
// →       - logging
Python
import 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))
CLI (xq + yq)
# 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
Go
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
}

Frequently Asked Questions

Is XML to YAML conversion lossless?
Not fully. XML attributes, comments, processing instructions, and CDATA sections have no native YAML equivalent. Attributes can be preserved as prefixed keys (_attr or @attr), but comments and processing instructions are discarded. If you need to round-trip back to XML, verify that attributes and namespace declarations survived the conversion.
How are XML attributes represented in YAML?
Most converters prefix attribute names with an underscore (_) or @ symbol to separate them from child element keys. For example, <server port="8080"> becomes server:\n _port: "8080". The specific prefix depends on the library or tool you use.
What happens to repeated XML elements during conversion?
When the same element tag appears multiple times under one parent, the converter groups them into a YAML sequence (list). For example, two <item> siblings become item:\n - value1\n - value2. A single <item> stays as a scalar value unless force-array mode is enabled.
Can I convert YAML back to XML?
Yes, but the result depends on how the original conversion handled attributes and types. If attributes were preserved with prefixed keys, a YAML-to-XML converter can reconstruct them. ToolDeck has a YAML to XML tool for the reverse direction. Be aware that YAML native types (booleans, numbers) will become text strings in XML.
Why does the YAML output quote some values?
YAML has native types: true/false are booleans, bare numbers become integers or floats, and yes/no/on/off are also booleans in YAML 1.1. If your XML contains text like "true" or "3306" that should remain a string, the converter quotes it to prevent YAML parsers from reinterpreting the value. This is correct behavior, not an error.
How do I handle large XML files?
Browser-based converters work well for files up to a few megabytes. For larger files (10MB+), use a streaming approach: parse XML with Python's iterparse or Node.js sax, build the intermediate object incrementally, then serialize to YAML. Tools like yq can also convert XML to YAML directly from the command line without loading the full document into memory.
What is the difference between XML to YAML and XML to JSON conversion?
Both conversions face the same challenge of mapping XML attributes and repeated elements to a different data model. The main difference is in the output format. JSON is strict (no comments, explicit types, strict syntax), while YAML is a superset of JSON that adds human-friendly features: comments, multi-line strings, anchors, and aliases. Choose JSON when the consumer is an API or JavaScript runtime. Choose YAML when the consumer is a human editing configuration files.