Skip to content

Commit 5aef1f2

Browse files
Creation of element when object is null or empty
Allows an empty elment to be created from an empty of null object, such as <element />
1 parent 1a351a1 commit 5aef1f2

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

XMap.Test/XmlMapperToXmlTests.cs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,68 @@ public void SetsTwoAttributesFromProperty()
209209
Assert.Equal("Collins", actual.Attribute("lname").Value);
210210
}
211211

212+
[Fact]
213+
public void CreateElementFromEmptyCollection()
214+
{
215+
var astronautMapper = new XmlMapper<Astronaut>
216+
{
217+
{"name", a => a.Name},
218+
};
219+
220+
var mapper = new XmlMapper<Spaceship>
221+
{
222+
{"crew/member", o => o.Crew, astronautMapper},
223+
};
224+
225+
var spaceship = new Spaceship
226+
{
227+
Crew = new List<Astronaut>(),
228+
};
229+
230+
var actual = mapper.ToXml(spaceship, "spaceship");
231+
232+
Assert.Equal("<crew />", actual.Element("crew").ToString());
233+
234+
}
235+
236+
[Fact]
237+
public void CreateElementFromNullCollection()
238+
{
239+
var astronautMapper = new XmlMapper<Astronaut>
240+
{
241+
{"name", a => a.Name},
242+
};
243+
244+
var mapper = new XmlMapper<Spaceship>
245+
{
246+
{"crew/member", o => o.Crew, astronautMapper},
247+
};
248+
249+
var spaceship = new Spaceship
250+
{
251+
Crew = null,
252+
};
253+
254+
var actual = mapper.ToXml(spaceship, "spaceship");
255+
256+
Assert.Equal("<crew />", actual.Element("crew").ToString());
257+
}
258+
259+
[Fact]
260+
public void CreateElementFromNullObject()
261+
{
262+
var astronautMapper = new XmlMapper<Astronaut>
263+
{
264+
{"name", a => a.Name},
265+
};
266+
267+
Astronaut astronaut = null;
268+
269+
var actual = astronautMapper.ToXml(astronaut, "astronaut");
270+
271+
Assert.Equal("<astronaut />", actual.ToString());
272+
}
273+
212274
static Tuple<string, string> Split(string source)
213275
{
214276
var bits = source.Split(' ');

XMap/XmlMapper.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,8 @@ private void MapCollectionElements(XElement xml, T obj)
275275
/// </returns>
276276
public XElement ToXml(T obj, XName elementName)
277277
{
278-
return ToXml(obj, new XElement(elementName));
278+
var element = new XElement(elementName);
279+
return obj == null ? element : ToXml(obj, new XElement(elementName));
279280
}
280281

281282
/// <summary>
@@ -343,6 +344,8 @@ private void MapToAttributes(T obj, XElement xml)
343344
public XElement ToXml(IEnumerable<T> objs, XName containerName, XName childName)
344345
{
345346
var container = new XElement(containerName);
347+
if (objs == null) return container;
348+
346349
foreach (XElement child in ToXml(objs, childName))
347350
{
348351
container.Add(child);

0 commit comments

Comments
 (0)