strong-xml icon indicating copy to clipboard operation
strong-xml copied to clipboard

Error with Option<Cow<str>> element when single tag

Open mskrip opened this issue 5 years ago • 1 comments

Case

XML source file can contain element <Element/> or <Element>text</Element> or not contain the span. The type for it should be defined as:


#[derive(Debug, PartialEq, XmlRead, XmlWrite)]
#[xml(tag = "Parent")]
pub struct Parent<'a> {
    #[xml(child = "Element")]
    pub element: Option<Element<'a>>,
}

#[derive(Debug, PartialEq, XmlRead, XmlWrite)]
#[xml(tag = "Element")]
pub struct Element<'a> {
    #[xml(text)]
    pub content: Option<Cow<'a, str>>,
}

Expected behavior

  1. <Element>text<Element/> => text is loaded into the instance
  2. <Element/> => parent->element->content should be None
  3. not specified => parent->element should be None

Or in case of defining the Element with flatten_text the case 2 and 3 can either have the same outcome or parent-element->text should be an empty/default value (empty string) for case 2.

Actual behavior

Case 1 and 3 work as expected. With case 2, however, I'm getting the following error:

UnexpectedToken { token: "ElementEnd { end: Empty, span: StrSpan(\"/>\" 2005..2007) }" }'

Same thing when using flatten_text.

Related issue

Having

#[derive(Debug, PartialEq, XmlRead, XmlWrite)]
#[xml(tag = "Element")]
pub struct Element<'a> {
    #[xml(text)]
    pub content: Option<Cow<'a, str>>,
}

Has error

   | #[derive(Debug, PartialEq, XmlRead, XmlWrite)]
   |                                     ^^^^^^^^ expected `str`, found reference
   |
   = note: expected reference `&str`
              found reference `&&std::option::Option<std::borrow::Cow<'_, str>>`

Although it says that Option<Cow<str>> should be supported. I can implement the XmlWrite myself, but that results in the issue mentioned above.

mskrip avatar Jul 03 '20 12:07 mskrip

Thanks for reporting this and apologize for the delay in replying. #[xml(text)] doesn't support Option<Cow<str>> now. As a workaround, you can use Cow<str> directly, it will fall back to empty string if text element is not present.

I'm going to implement this in the next couple of days.

PoiScript avatar Aug 04 '20 10:08 PoiScript