About XML to Swift
Paste your XML and get Swift struct definitions conforming to Codable. Generates CodingKeys enums when XML attributes need renaming.
Frequently Asked Questions
What is XML to Swift struct generation?
XML to Swift struct generation analyses an XML document and produces Swift struct definitions that model its element and attribute structure. The generated structs can be used with XMLDecoder from Foundation or with the XMLCoder open-source library.
How do I parse XML in Swift using XMLParser (SAX parser)?
Implement XMLParserDelegate and handle didStartElement, foundCharacters, and didEndElement callbacks. SAX parsing is memory-efficient for large documents but requires manual state tracking. The generated Codable struct acts as the target model — hydrate it in the delegate callbacks as elements are encountered.
Should I use Codable or XMLParser for XML parsing in Swift?
Swift's Codable protocol does not natively support XML. Use XMLParser (event-driven, low memory) or a third-party library like SwiftyXMLParser or AEXML (DOM-style, easier to use). Codable is ideal for JSON; for XML, pick the library that matches your document size and navigation needs.
How are XML namespaces handled in Swift XML parsing?
XMLParser provides the namespaceURI parameter in didStartElement callbacks. Use it to distinguish elements with the same local name but different namespaces. The generated Swift struct ignores namespaces — in your parser delegate, filter by both localName and namespaceURI if the document uses multiple namespaces.
Can I convert the generated Swift struct back to XML?
Not automatically — Swift has no built-in XML serialiser for custom types. Use a library like XMLCoder (supports Codable for XML) which adds encode/decode XML support similar to JSONEncoder. Add @Attribute annotations to mark which properties should be XML attributes vs elements.
Advertisement300 × 250
Advertisement300 × 250