Skip to content

Commit

Permalink
Add XmlFormatter.ToXElement()
Browse files Browse the repository at this point in the history
  • Loading branch information
menees committed Oct 14, 2023
1 parent b27dff4 commit 127d570
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
32 changes: 26 additions & 6 deletions src/Menees.Chords/Formatters/XmlFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
#region Using Directives

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Linq;

#endregion

/// <summary>
/// Formats an <see cref="IEntryContainer"/> as flat or indented text.
/// Formats an <see cref="IEntryContainer"/> as XML.
/// </summary>
public sealed class XmlFormatter : ContainerFormatter
{
Expand Down Expand Up @@ -37,12 +38,20 @@ public XmlFormatter(IEntryContainer container)
/// <inheritdoc/>
public override string ToString()
{
if (this.root is null)
{
this.Format();
}
this.EnsureRoot();
return this.root.ToString();
}

/// <summary>
/// Gets the formatted document as an XElement.
/// </summary>
public XElement ToXElement()
{
this.EnsureRoot();

return this.root?.ToString() ?? string.Empty;
// Clone the root element so a caller can't mess with our private instance.
XElement result = new(this.root);
return result;
}

#endregion
Expand Down Expand Up @@ -118,5 +127,16 @@ private static void AddEntry(Entry entry, XElement container)
container.Add(element);
}

[MemberNotNull(nameof(this.root))]
private void EnsureRoot()
{
if (this.root is null)
{
this.Format();
}

Conditions.RequireNonNull(this.root);
}

#endregion
}
10 changes: 10 additions & 0 deletions tests/Menees.Chords.Tests/Formatters/XmlFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ public void ToStringTest()
XElement.Parse(text).ShouldNotBeNull();
}

[TestMethod]
public void ToXElementTest()
{
Document document = TestUtility.LoadSwingLowSweetChariot();
XmlFormatter formatter = new(document);
XElement element = formatter.ToXElement();
Debug.WriteLine(element);
element.Name.LocalName.ShouldBe(nameof(Document));
}

[TestMethod]
public void AnnotatedTest()
{
Expand Down

0 comments on commit 127d570

Please sign in to comment.