Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/DocumentFormat.OpenXml.Framework/OpenXmlElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -796,11 +796,30 @@ public void RemoveNamespaceDeclaration(string prefix)
/// Finds the first child element in type T.
/// </summary>
/// <typeparam name="T">Type of element.</typeparam>
/// <returns></returns>
/// <returns>The first child element of type T or null</returns>
public T? GetFirstChild<T>()
where T : OpenXmlElement
=> ChildElements.First<T>();

/// <summary>
/// Finds the first child element of <typeparam ref="T"/> or adds a new element if it does not exist.
/// </summary>
/// <typeparam name="T">Type of element.</typeparam>
/// <returns>The new or existing OpenXmlElement</returns>
public T GetOrAddFirstChild<T>()
where T : OpenXmlElement, new()
{
var child = GetFirstChild<T>();

if (child is null)
{
child = new T();
AppendChild(child);
}

return child;
}

/// <summary>
/// Gets the OpenXmlElement element that immediately precedes the current OpenXmlElement element.
/// Returns null (Nothing in Visual Basic ) if there is no preceding OpenXmlElement element.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ DocumentFormat.OpenXml.OpenXmlElement.Features.get -> DocumentFormat.OpenXml.Fea
DocumentFormat.OpenXml.OpenXmlElement.GetAttribute(string! localName, string! namespaceUri) -> DocumentFormat.OpenXml.OpenXmlAttribute
DocumentFormat.OpenXml.OpenXmlElement.GetAttributes() -> System.Collections.Generic.IList<DocumentFormat.OpenXml.OpenXmlAttribute>!
DocumentFormat.OpenXml.OpenXmlElement.GetFirstChild<T>() -> T?
DocumentFormat.OpenXml.OpenXmlElement.GetOrAddFirstChild<T>() -> T!
DocumentFormat.OpenXml.OpenXmlElement.HasAttributes.get -> bool
DocumentFormat.OpenXml.OpenXmlElement.InsertAfterSelf<T>(T! newElement) -> T!
DocumentFormat.OpenXml.OpenXmlElement.InsertBeforeSelf<T>(T! newElement) -> T!
Expand Down
15 changes: 15 additions & 0 deletions test/DocumentFormat.OpenXml.Tests/ofapiTest/OpenXmlElementTest2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,5 +216,20 @@ internal override void ConfigureMetadata(ElementMetadata.Builder builder)
private class ChildElement : OpenXmlLeafElement
{
}

/// <summary>
/// A test for OpenXmlElement.GetOrAddFirstChild.
/// </summary>
[Fact]
public void GetOrAddFirstChildTest()
{
Paragraph p = new();
Run r = p.GetOrAddFirstChild<Run>();
Assert.NotNull(r);
Assert.Same(r, p.GetFirstChild<Run>());

var r2 = p.GetOrAddFirstChild<Run>();
Assert.Same(r, r2);
}
}
}
Loading