I am trying to write a function to extract both the data and the attribute data from an XMLElement in the same pass. I have followed the examples from Mathematica's Transforming XML tutorial and the Mathematica StackExchange solution here
Extract attribute data from an XMLElement
However, the function I wrote returns the empty list. I believe the Cases function traverses the XML string once and, consequently, does not parse the XMLElement for the second time as I thought it would.
My MWL starts with reading the fleetXMLString from file with Import[fName]
XMLObject[
"Document"][{XMLObject["Declaration"]["Version" -> "1.0",
"Encoding" -> "utf-8"]},
XMLElement[
"Fleet", {}, {XMLElement[
"SomeVehicle", {}, {XMLElement["Name", {}, {"BJ#00"}],
XMLElement[
"Bus", {}, {XMLElement["Shape", {}, {"parallelepiped"}],
XMLElement["Length", {"unit" -> "Distance"}, {"0.5"}],
XMLElement["Width", {"unit" -> "Distance"}, {"0.4"}],
XMLElement["Height", {"unit" -> "Distance"}, {"0.3"}],
XMLElement["Density", {"unit" -> "Density"}, {"500.0"}]}]}],
XMLElement[
"SomeVehicle", {}, {XMLElement["Name", {}, {"BJ#01"}],
XMLElement[
"Bus", {}, {XMLElement["Shape", {}, {"parallelepiped"}],
XMLElement["Length", {"unit" -> "Distance"}, {"0.5"}],
XMLElement["Width", {"unit" -> "Distance"}, {"0.4"}],
XMLElement["Height", {"unit" -> "Distance"}, {"0.3"}],
XMLElement[
"Density", {"unit" -> "Density"}, {"500.0"}]}]}]}], {}]
The two functions below give the expected results
BusPhysParam[xmlString_, name_, pName_] :=
Cases[
Cases[xmlString,
XMLElement["SomeVehicle", _, {___,
XMLElement["Name", _, {name}], ___}], Infinity],
XMLElement["Bus", _, {___,
XMLElement[pName, _, {dim_}], ___}] :> ToExpression[dim],
Infinity]
BusPhysParam[fleetXMLString, "BJ#00", "Width"]
{0.4}
and
BusPhysParamUnit[xmlString_, name_, pName_] :=
Cases[
Cases[xmlString,
XMLElement["SomeVehicle", _, {___,
XMLElement["Name", _, {name}], ___}], Infinity],
XMLElement["Bus", _, {___,
XMLElement[pName, {___, "unit" -> unit_}, ___], ___}] :> unit,
Infinity]
BusPhysParamUnit[fleetXMLString, "BJ#00", "Width"]
{Distance}
However, this function returns the empty list
BusPhysParamMod[xmlString_, name_, pName_] :=
Cases[
Cases[xmlString,
XMLElement["SomeVehicle", _, {___,
XMLElement["Name", _, {name}], ___}], Infinity],
XMLElement["Bus", _, {___,
XMLElement[pName, _, {dim_}], ___,
XMLElement[pName, {___, "unit" -> unit_}, ___]}] :> {ToExpression[dim],
unit}, Infinity]
BusPhysParamMod[fleetXMLString, "BJ#00", "Width"]
Is there a way to extract both the value and attribute at the same time? Thank you! B