Skip to content

Deserialize unconsistent XML to a normalized Array #188

Open
@jzfgo

Description

@jzfgo

Hi,

I have this weird looking XML and I'm trying to convert it to a simple array.

So far I've managed to do most of it with keyValue and repeatingElements deserializers and a custom one for the <Child/> element.

My problem is with the <Context/> elements. Since they aren't wrapped in a parent element, I can't treat them like repeating elements and if I parse <Query/>’s children like key-value elements, I only get the first <Context/> element.

Any suggestions?

This an example of the XML that I'm trying to parse:

<Query>
	<Checkin>2020-08-01</Checkin>
	<Nights>4</Nights>
	<PropertyList>
		<Property>my-hotel</Property>
	</PropertyList>
	<DeadlineMs>500</DeadlineMs>
	<Context>
		<Occupancy>3</Occupancy>
		<UserCountry>CA</UserCountry>
		<UserDevice>tablet</UserDevice>
	</Context>
	<Context>
		<Occupancy>4</Occupancy>
		<OccupancyDetails>
			<NumAdults>2</NumAdults>
			<Children>
				<Child age="8"/>
				<Child age="5"/>
			</Children>
		</OccupancyDetails>
		<UserCountry>US</UserCountry>
		<UserDevice>mobile</UserDevice>
	</Context>
	<Context>
		<Occupancy>6</Occupancy>
		<OccupancyDetails>
			<NumAdults>4</NumAdults>
			<Children>
				<Child age="6"/>
				<Child age="10"/>
			</Children>
		</OccupancyDetails>
		<UserCountry>FR</UserCountry>
		<UserDevice>desktop</UserDevice>
	</Context>
</Query>

And this is the result that I would like to achieve:

[
	'Checkin' => '2020-08-01',
	'Nights' => 4,
	'PropertyList' => [
		'my-hotel',
	],
	'DeadlineMs' => 500,
	'Contexts' => [
		[
			'Occupancy' => 3,
			'UserCountry' => 'CA',
			'UserDevice' => 'tablet',
		],
		[
			'Occupancy' => 4,
			'OccupancyDetails' => [
				'NumAdults' => 2,
				'Children' => [
					8,
					5,
				],
			]
			'UserCountry' => 'US',
			'UserDevice' => 'mobile',
		],
		[
			'Occupancy' => 6,
			'OccupancyDetails' => [
				'NumAdults' => 4,
				'Children' => [
					6,
					10,
				],
			]
			'UserCountry' => 'FR',
			'UserDevice' => 'desktop',
		],
	],
];

Best,
Javier.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions