Skip to content

Customization of namespace prefixes #252

Merged
merged 3 commits into from
Nov 20, 2022
Merged

Customization of namespace prefixes #252

merged 3 commits into from
Nov 20, 2022

Conversation

valentiay
Copy link
Contributor

@valentiay valentiay commented Nov 20, 2022

This PR adds capability to configure namespace prefixes in encoders. Closes #230.

Example

Scala 2

@XmlnsDef("https://example.org/schema", true)
object schema

@XmlCodecNs("foo", schema)
case class Foo(@xmlns(schema) bar: String)

println(XmlEncoder[Foo].encode(Foo("string")))

or

case object schema
implicit val schemaNs: Namespace[schema.type] =
  Namespace.mkInstance(
    uri = "https://example.org/schema",
    preferredPrefix = Some("schema"),
  )

case class Foo(@xmlns(schema) bar: String)
implicit val fooEncoder: XmlEncoder[Foo] = deriveXmlEncoder("foo", schema)

println(XmlEncoder[Foo].encode(Foo("string")))

Output:

<?xml version='1.0' encoding='UTF-8'?>
<schema:foo xmlns:schema="https://example.org/schema">
    <schema:bar>string</schema:bar>
</schema:foo>

Scala 3

case object schema
given Namespace[schema.type] =
  Namespace.mkInstance(
    uri = "https://example.org/schema",
    preferredPrefix = Some("schema"),
  )

case class Foo(@xmlns(schema) bar: String)
given XmlEncoder[Foo] = deriveXmlEncoder("foo", schema)

println(XmlEncoder[Foo].encode(Foo("string")))

Output:

<?xml version='1.0' encoding='UTF-8'?>
<schema:foo xmlns:schema="https://example.org/schema">
    <schema:bar>string</schema:bar>
</schema:foo>

Note: If preferred prefix is not specified, encoder will automatically generate prefix. This is still the default behavior.

case object schema
given Namespace[schema.type] =
  Namespace.mkInstance("https://example.org/schema")

case class Foo(@xmlns(schema) bar: String)
given XmlEncoder[Foo] = deriveXmlEncoder("foo", schema)

println(XmlEncoder[Foo].encode(Foo("string")))
<?xml version='1.0' encoding='UTF-8'?>
<ans1:foo xmlns:ans1="https://example.org/schema">
    <ans1:bar>string</ans1:bar>
</ans1:foo>

This document is equal to the documents in examples above. Prefix names don't change the structure of XML document, as far as they are associated with same URIs

@valentiay valentiay added this to the v0.18.0 milestone Nov 20, 2022
@valentiay valentiay merged commit 150d88e into master Nov 20, 2022
@valentiay valentiay deleted the issue-320 branch November 20, 2022 10:35
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Namespace prefix support
1 participant