media-io / yaserde

Yet Another Serializer/Deserializer
MIT License
174 stars 58 forks source link

Is there a way to make a struct with alternative namespace? #160

Closed RinChanNOWWW closed 1 year ago

RinChanNOWWW commented 1 year ago

For example

#[derive(Debug, YaDeserialize, YaSerialize, Default)]
#[yaserde(namespace = "{namespace}")]
pub struct MyStruct {
   // ...
}

I want to the {namespace} be alternative.

Or, can I not specify #[yaserde(namespace = "{namespace}")] if the XML has a namespace?

If I don't specify namespace, it will return Error: bad namespace for xxx, found xxxx

RinChanNOWWW commented 1 year ago

PTAL @MarcAntoine-Arnaud

MarcAntoine-Arnaud commented 1 year ago

Hello, Sorry for the delay. For namespace, the derive cannot take variable. Some example are provided in the repo, like https://github.com/media-io/yaserde/blob/master/examples/src/bbigras_namespace.rs 2 attributes are important :

Is it clear ?

Best regards

RinChanNOWWW commented 1 year ago

Thanks for answering.

What is the best way to deal with the case if the namespace could change? Make two different structs? Is there a simpler way?

MarcAntoine-Arnaud commented 1 year ago

Yes it's the simplest. And using flatten is great to do:

#[derive(YaDeserialize)]
#[yaserde ...]
struct MyNamespace1 {
  #[yaserde(flatten)]
  fields: Fields
}

#[derive(YaDeserialize)]
#[yaserde ...]
struct MyNamespace2 {
  #[yaserde(flatten)]
  fields: Fields
}

#[derive(YaDeserialize)]
struct Fields {
  ...
}

Like that you didn't re-wrote fields.

RinChanNOWWW commented 1 year ago

Thanks.