I am trying to parse an XML file nodes and attributes. Within the file there is a set of nodes with attributes. Nested XML structure is similar to a data frame with a I want to parse this into a data frame.
Here is an example file:
<?xml version="1.0" encoding="UTF-8"?>
<TrackMate version="3.8.0">
<Model spatialunits="µm" timeunits="sec">
<AllTracks>
<Track name="Track_2" TRACK_ID="2" NUMBER_SPOTS="140" NUMBER_GAPS="0" >
<Edge SPOT_SOURCE_ID="960769" SPOT_TARGET_ID="960778" LINK_COST="0.08756957830926632" />
<Edge SPOT_SOURCE_ID="958304" SPOT_TARGET_ID="958308" LINK_COST="1.4003359672950089" />
<Edge SPOT_SOURCE_ID="958316" SPOT_TARGET_ID="958322" LINK_COST="1.6985623204008202" />
</Track>
<Track name="Track_145" TRACK_ID="145" NUMBER_SPOTS="141" NUMBER_GAPS="0" >
<Edge SPOT_SOURCE_ID="961623" SPOT_TARGET_ID="961628" LINK_COST="2.2678642015413755" />
<Edge SPOT_SOURCE_ID="962122" SPOT_TARGET_ID="962127" LINK_COST="38.20777704254654" />
<Edge SPOT_SOURCE_ID="961869" SPOT_TARGET_ID="961873" LINK_COST="0.2895609647324684" />
</Track>
</AllTracks>
</Model>
</TrackMate>
I would like like create a data frame with all attributes of edges and parent's TRACK_ID attribute. I can readily create the data frame with all the edges' attributes with this:
edges = data.frame(t(data.frame(xml_attrs(xml_find_all(xmlDoc, xpath = paste0('/TrackMate/Model/AllTracks//Edge'))))))
row.names(edges) = NULL
But then the corresponding track ID is lost. I can solve this with a for loop but that is often not the "R way". I was wondering if, there are is a simpler solution? (e.g. with xpath query).
So the final desired output would be this data frame:

Edit: this comes closer but the then Track nodes and Edge nodes are mixed within a list.
xml_find_all(xmlDoc, xpath = paste0('/TrackMate/Model/AllTracks//Edge | /TrackMate/Model/AllTracks/Track'))