Consider the following MWE (based on the same logic as Update mesh over time - #2 by dokken):
from mpi4py import MPI
import dolfinx
mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 10, 10)
mesh.name = "InitialMesh"
V = dolfinx.fem.FunctionSpace(mesh, ("Lagrange", 1))
u = dolfinx.fem.Function(V)
u.interpolate(lambda x: x[0] * x[1])
u.name = "f"
xdmf = dolfinx.io.XDMFFile(MPI.COMM_WORLD, "functions.xdmf", "w")
xdmf.write_mesh(mesh)
xdmf.write_function(u, mesh_xpath=f"/Xdmf/Domain/Grid[@Name='{mesh.name}']")
mesh.topology.create_connectivity(1, 2)
r_mesh = dolfinx.mesh.refine(mesh)
r_mesh.name = "Refined"
Vr = dolfinx.fem.FunctionSpace(r_mesh, ("Lagrange", 1))
ur = dolfinx.fem.Function(Vr)
ur.interpolate(lambda x: x[0] * x[1])
ur.name = "f"
xdmf.write_mesh(r_mesh)
xdmf.write_function(
ur, t=1, mesh_xpath=f"/Xdmf/Domain/Grid[@Name='{r_mesh.name}']")
xdmf.close()