How to write stresses to a xdmf file?

You should use dolfinx.fem.Expression to interpolate the stress into a suitable function space (DG of some order) and use dolfinx.io.VTXWriter to write it to file preserving the function space.
You can see how B is computed in Electromagnetics example — FEniCSx tutorial
E.g.

W = VectorFunctionSpace(mesh, ("DG", 0))
B = Function(W)
B_expr = Expression(as_vector((A_z.dx(1), -A_z.dx(0))), W.element.interpolation_points())
B.interpolate(B_expr)

https://jsdokken.com/fenics22-tutorial/heat_eq.html#post-processing-without-projections
or
https://jsdokken.com/dolfinx-tutorial/chapter2/linearelasticity_code.html#stress-computation

2 Likes