YAML to XML

Convert YAML to XML format

Try an example

YAML Input

XML Output

Runs locally · Safe to paste secrets
XML will appear here…
Also try:YAML to JSON

What Is YAML to XML Conversion?

YAML to XML conversion transforms data written in YAML (YAML Ain't Markup Language) into XML (Extensible Markup Language). YAML uses indentation and minimal punctuation to represent structured data, while XML uses opening and closing tags with an explicit hierarchy. Converting between the two is a routine task when systems that consume XML need to receive data originally authored in YAML.

YAML was designed for human readability. Configuration files for tools like Kubernetes, Ansible, Docker Compose, and GitHub Actions are written in YAML because it is compact and easy to edit by hand. XML, defined by the W3C XML 1.0 specification, has been the default data interchange format in enterprise systems, SOAP web services, and document-centric workflows for decades. When a YAML-authored configuration must feed into an XML-based pipeline, conversion is required.

The mapping between YAML and XML is not one-to-one. YAML supports data types like booleans, integers, floats, and null natively, while XML treats all content as text unless a schema (XSD or DTD) defines types externally. YAML sequences (lists) have no direct XML equivalent and must be represented as repeated elements. Knowing these differences helps you predict the output and avoid surprises.

Why Use This YAML to XML Converter?

Manually rewriting YAML as XML is tedious and error-prone, especially for deeply nested structures. This converter handles the structural translation instantly.

Instant Conversion
Paste YAML and get formatted XML output immediately. No need to write a script or install a CLI tool for one-off conversions.
🔒
Privacy-First Processing
All conversion runs in your browser. Your YAML data, which often contains server addresses, credentials, and infrastructure details, never leaves your machine.
📋
No Account Required
Use the converter without signing up, logging in, or providing an email. Open the page and start converting.
🌐
Handles Nested Structures
Supports deeply nested YAML mappings, sequences, mixed types, and multiline strings. The output preserves hierarchy with proper XML indentation.

YAML to XML Use Cases

Frontend Development
Convert YAML mock data into XML format for testing XML parsers, XSLT transformations, or components that expect XML responses from APIs.
Backend Integration
Transform YAML configuration into XML when integrating with legacy Java services that use Spring XML config, Maven POM files, or SOAP endpoints.
DevOps and CI/CD
Convert Kubernetes or Ansible YAML manifests into XML for tools that require XML input, such as Jenkins pipeline configurations or certain monitoring systems.
QA and Testing
Generate XML test fixtures from YAML definitions. YAML is easier to maintain as test data, and converting to XML at test time keeps fixtures readable.
Data Engineering
Convert YAML-formatted ETL configs or schema definitions into XML for pipelines that consume XML. Common in healthcare (HL7), finance (FpML), and government data systems.
Learning and Prototyping
Students and newcomers can paste YAML and see the equivalent XML structure side by side, which helps build intuition for how hierarchical data maps between formats.

YAML to XML Type Mapping Reference

YAML data types do not map directly to XML. This table shows how each YAML construct translates to its XML equivalent. Understanding these rules helps you predict the output and troubleshoot unexpected results.

YAML TypeYAML ExampleXML Output
Mapping (key: value){ name: Alice }<name>Alice</name>
Sequence (- item)- apple\n- banana<item>apple</item><item>banana</item>
Nested mappinguser:\n name: Alice<user><name>Alice</name></user>
Scalar (string)greeting: hello world<greeting>hello world</greeting>
Scalar (number)count: 42<count>42</count>
Scalar (boolean)active: true<active>true</active>
Nullvalue: null<value/>
Multiline stringbio: |\n Line one\n Line two<bio>Line one\nLine two</bio>

YAML vs XML: Format Differences

YAML and XML solve the same problem — structured data representation — with different trade-offs. Neither is universally better; the right choice depends on who or what consumes the data.

YAML
Whitespace-delimited, no closing tags. Supports native types (bool, int, float, null). Comments with #. Compact for configuration and human editing. Parsed by libraries like PyYAML, js-yaml, and gopkg.in/yaml.
XML
Tag-based with explicit open/close pairs. All values are text by default; types require a schema (XSD). Supports attributes, namespaces, mixed content, and processing instructions. Parsed by every major language's standard library.
FeatureYAMLXML
SyntaxIndentation-basedTag-based (&lt;tag&gt;...&lt;/tag&gt;)
Data typesNative (string, int, bool, null, float)Text only (schema adds types)
Comments# inline comments<!-- block comments -->
AttributesNo native supportYes (&lt;tag attr="val"&gt;)
NamespacesNot supportedYes (xmlns:prefix)
File sizeSmaller (no closing tags)Larger (verbose tags)

Code Examples

How to convert YAML to XML programmatically in different languages and environments:

JavaScript (Node.js)
import { parseDocument } from 'yaml'
import { js2xml } from 'xml-js'

const yamlStr = `
server:
  host: localhost
  port: 8080
  ssl: true
`

const data = parseDocument(yamlStr).toJSON()
const xml = js2xml({ root: data }, { compact: true, spaces: 2 })
console.log(xml)
// → <root>
// →   <server>
// →     <host>localhost</host>
// →     <port>8080</port>
// →     <ssl>true</ssl>
// →   </server>
// → </root>
Python
import yaml
import xml.etree.ElementTree as ET

yaml_str = """
database:
  host: db.example.com
  port: 5432
  credentials:
    user: admin
    password: secret
"""

data = yaml.safe_load(yaml_str)

def dict_to_xml(tag, d):
    elem = ET.Element(tag)
    for key, val in d.items():
        child = ET.SubElement(elem, key)
        if isinstance(val, dict):
            child.extend(dict_to_xml(key, val))
            elem.remove(child)
            elem.append(dict_to_xml(key, val))
        else:
            child.text = str(val)
    return elem

root = dict_to_xml('root', data)
ET.indent(root, space='  ')
print(ET.tostring(root, encoding='unicode'))
# → <root>
# →   <database>
# →     <host>db.example.com</host>
# →     <port>5432</port>
# →     ...
# →   </database>
# → </root>
Go
package main

import (
    "encoding/xml"
    "fmt"
    "gopkg.in/yaml.v3"
)

type Server struct {
    XMLName xml.Name `xml:"server"`
    Host    string   `yaml:"host" xml:"host"`
    Port    int      `yaml:"port" xml:"port"`
    SSL     bool     `yaml:"ssl"  xml:"ssl"`
}

func main() {
    yamlData := []byte("host: localhost\nport: 8080\nssl: true")

    var s Server
    yaml.Unmarshal(yamlData, &s)

    xmlBytes, _ := xml.MarshalIndent(s, "", "  ")
    fmt.Println(xml.Header + string(xmlBytes))
    // → <?xml version="1.0" encoding="UTF-8"?>
    // → <server>
    // →   <host>localhost</host>
    // →   <port>8080</port>
    // →   <ssl>true</ssl>
    // → </server>
}
CLI (yq + xq)
# Using yq (YAML processor) with xq (XML wrapper around jq)
# Install: pip install yq

# Convert YAML file to XML
yq -x . config.yaml
# → <host>localhost</host><port>8080</port>

# Pipe inline YAML through conversion
echo "name: Alice" | yq -x .
# → <name>Alice</name>

Frequently Asked Questions

Can YAML sequences be represented in XML?
Yes, but XML has no native list type. YAML sequences are typically converted to repeated XML elements with the same tag name. For example, a YAML list under the key "items" becomes multiple &lt;item&gt; child elements. Some converters wrap them in a parent &lt;items&gt; element for clarity.
What happens to YAML comments during conversion?
YAML comments (lines starting with #) are discarded during conversion. Most YAML parsers strip comments when building the data structure, so they are not available for the XML output. If you need to preserve comments, you would need a YAML parser that retains them, such as ruamel.yaml in Python.
How are YAML anchors and aliases handled?
YAML anchors (&name) and aliases (*name) are resolved before conversion. The parser expands aliases into their full values, so the resulting XML contains the complete data without any anchor references. This means the XML output may be larger than the YAML input if anchors were used to avoid repetition.
Is the conversion reversible (XML back to YAML)?
Partially. You can convert XML to YAML, but the result may not match the original YAML exactly. XML attributes have no YAML equivalent and are typically represented as special keys (e.g., @attribute). Type information is also lost since XML treats everything as text, so numbers and booleans in the original YAML become strings after a round-trip.
How do I handle XML attributes when converting from YAML?
YAML has no native concept of attributes. A common convention is to prefix keys with @ to indicate they should become XML attributes rather than child elements. For example, "@id: 42" under a mapping would produce &lt;element id="42"&gt;. This convention is used by libraries like xml-js and xmltodict.
What is the maximum YAML file size this tool can handle?
The converter runs in your browser, so the limit depends on your device's available memory. Files up to a few megabytes convert without issues on modern hardware. For very large files (50 MB+), use a command-line tool like yq or a Python script with PyYAML and lxml, which handle streaming and memory more efficiently.
Why does my YAML produce invalid XML output?
The most common cause is YAML keys that are not valid XML element names. XML element names cannot start with a number, contain spaces, or use most special characters. Keys like "2nd-item" or "my key" will produce invalid XML. Rename the offending keys or use a converter that sanitizes names automatically (e.g., replacing spaces with underscores and prepending an underscore to numeric-starting names).