Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create xml from struct in rust?

Tags:

rust

serde

I try to create a xml string from a struct in rust. The struct is nested and I'm always getting duplicate tags in xml. I'm using serde-xml-rs version 0.5.1.

#[derive(Serialize, Debug)]
struct A {
   #[serde(rename(serialize = "B"))]
   pub b: B
}

#[derive(Serialize, Debug)]
struct B {
    pub c: String
}

let foo = A {
    b: B {
        c: "bar".to_string()
    }
};

println!("{:?}", to_string(&foo));

This produces

<A>
    <B>
        <B>
            <c>bar</c>
        </B>
    </B>
</A>

What I expect:

<A>
    <B>
        <c>bar</c>
    </B>
</A>

How can I get just one B tag?

like image 938
chocolate cake Avatar asked Dec 10 '25 07:12

chocolate cake


1 Answers

You can change the B struct to avoid it emitting a <B> tag like this:

#[derive(Serialize, Debug)]
struct B {
    pub c: String,
    #[serde(flatten, skip)]
    pub _d: (),
}
like image 77
jonasbb Avatar answered Dec 12 '25 01:12

jonasbb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!