Skip to content

Ignore namespace #41

@geny200

Description

@geny200

Based on #3 issue - it was closed, but was added only ability to delete Namespace, it's not "true" ignore (because if the Namespace is specified in the model in the code, it'll still be required during decoding). My case: I have a wrapper that adds nesting and provides Namespace, and I need to be able to decode and encode. In the case of encoding, I want the resulting xml to have Namespace, in the case of deserialization, I want it to be ignored.

Code example:

//> using dep dev.valentiay::phobos-core:0.26.0
//> using scala "2.13.16"

import phobos.Namespace
import phobos.configured.ElementCodecConfig
import phobos.decoding.{ElementDecoder, XmlDecoder}
import phobos.derivation.semiauto.{deriveElementDecoder, deriveElementEncoder, deriveXmlDecoderConfigured}
import phobos.encoding.{ElementEncoder, XmlEncoder}
import phobos.syntax.xmlns

object MyNamespace {
  type ns = MyNamespace.type
  implicit val ns: Namespace[ns] = Namespace.mkInstance[ns]("http://test.org/some", Some("my"))
}

final case class Wrapper[T](@xmlns(MyNamespace) foo: T)

object Wrapper {
  implicit def encoder[T: ElementEncoder]: ElementEncoder[Wrapper[T]] = deriveElementEncoder
  implicit def decoder[T: ElementDecoder]: ElementDecoder[Wrapper[T]] = deriveElementDecoder

  implicit def xmlEncoder[T: ElementEncoder]: XmlEncoder[Wrapper[T]] =
    XmlEncoder.fromElementEncoder[Wrapper[T]]("MyRoot")
  implicit def xmlDecoder[T: ElementDecoder]: XmlDecoder[Wrapper[T]] =
    deriveXmlDecoderConfigured[Wrapper[T]](
      "MyRoot",
      ElementCodecConfig.default.withRemoveNamespaces, // remove namespaces
    )
}

object Main extends App {

  // case 1
  println(XmlEncoder[Wrapper[String]].encodeUnsafe(Wrapper("bar")))
  // result: <?xml version='1.0' encoding='UTF-8'?><MyRoot><my:foo xmlns:my="http://test.org/some">bar</my:foo></MyRoot>

  // case 2
  println(XmlDecoder[Wrapper[String]].decode(
    """<?xml version='1.0' encoding='UTF-8'?><MyRoot><my:foo xmlns:my="http://leviy-soft.org/more">bar</my:foo></MyRoot>"""
  ))
  // result: Left(phobos.decoding.DecodingError: Error while decoding XML: Invalid namespace. Expected 'http://test.org/some',  but found ''
  //	In element 'foo'
  //		in element 'MyRoot'
  //     )

}

In second case I expects as a result Wrapper("bar")

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions