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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# 1.3.1

Released on tbd.

- Fixed `document.title` of XHTML documents always being empty
- Fixed `createDocument` not being available to scripts (AngleSharp.Js) until a document was parsed
- Added running the scripts of the XHTML elements of a navigated XML document

# 1.3.0

Released on Sunday, November 1 2026.
Expand Down
2 changes: 1 addition & 1 deletion src/AngleSharp.Xml.Docs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@anglesharp/xml",
"version": "1.3.0",
"version": "1.3.1",
"preview": true,
"description": "The doclet for the AngleSharp.Xml documentation.",
"keywords": [
Expand Down
68 changes: 68 additions & 0 deletions src/AngleSharp.Xml.Tests/Dom/Acid3Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
namespace AngleSharp.Xml.Tests.Dom
{
using AngleSharp.Dom;
using AngleSharp.Io;
using AngleSharp.Xml.Parser;
using NUnit.Framework;
using System;
using System.Linq;
using System.Threading.Tasks;

/// <summary>
/// Behavior the Acid3 test (acid3.acidtests.org) relies on.
/// </summary>
[TestFixture]
public class Acid3Tests
{
private const String XhtmlNamespace = "http://www.w3.org/1999/xhtml";

[Test]
public void TitleOfAnXhtmlDocumentUpdatesWithItsElement()
{
var document = BrowsingContext.New(Configuration.Default.WithXml()).OpenNewAsync().Result;
var doctype = document.Implementation.CreateDocumentType("html", "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
var xhtml = document.Implementation.CreateDocument(XhtmlNamespace, "html", doctype);
xhtml.DocumentElement.AppendChild(xhtml.CreateElement(XhtmlNamespace, "head"));
xhtml.DocumentElement.AppendChild(xhtml.CreateElement(XhtmlNamespace, "body"));
var title = xhtml.CreateElement(XhtmlNamespace, "title");
xhtml.DocumentElement.FirstChild.AppendChild(title);

Assert.AreEqual(String.Empty, xhtml.Title);

title.TextContent = " Sparrow ";

Assert.AreEqual("Sparrow", xhtml.Title);
}

[Test]
public async Task DocumentThatIsNotWellFormedFailsToOpen()
{
// showing the error instead is up to the application (IDocumentErrorHandler)
var context = BrowsingContext.New(Configuration.Default.WithXml());

try
{
await context.OpenAsync(res => res
.Address("http://localhost/xhtml.2")
.Content("<html xmlns='http://www.w3.org/1999/xhtml'><body><p><strong/> Parsing Test </strong></p></body></html>")
.Header(HeaderNames.ContentType, MimeTypeNames.Xml));
Assert.Fail("The parse error should propagate.");
}
catch (XmlParseException)
{
}
}

[Test]
public void ConfigurationNamesTheLibrarySoItsDomExtensionsAreFound()
{
var config = Configuration.Default.WithXml().WithXml();
var libraries = config.Services
.Where(m => m is not Delegate)
.Select(m => m.GetType().Assembly)
.Count(m => m == typeof(XmlParser).Assembly);

Assert.AreEqual(1, libraries);
}
}
}
17 changes: 17 additions & 0 deletions src/AngleSharp.Xml/Dom/Internal/XmlDocument.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
namespace AngleSharp.Xml.Dom
{
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Io;
using AngleSharp.Text;
using System;
using System.Linq;

/// <summary>
/// Represents a document node that contains only XML nodes.
Expand Down Expand Up @@ -72,8 +74,23 @@ public override Node Clone(Document owner, Boolean deep)

#region Helpers

/// <summary>
/// The title of an XHTML document is its first title element (in the HTML namespace).
/// </summary>
protected override String GetTitle()
{
var title = DocumentElement?.Descendants<IHtmlTitleElement>().FirstOrDefault();
return title?.TextContent.CollapseAndStrip() ?? base.GetTitle();
}

protected override void SetTitle(String value)
{
var title = DocumentElement?.Descendants<IHtmlTitleElement>().FirstOrDefault();

if (title is not null)
{
title.TextContent = value ?? String.Empty;
}
}

internal void SetValidity(Boolean isValid)
Expand Down
77 changes: 71 additions & 6 deletions src/AngleSharp.Xml/XmlConfigurationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
namespace AngleSharp
{
using AngleSharp.Browser;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using AngleSharp.Io;
using AngleSharp.Scripting;
using AngleSharp.Svg.Dom;
using AngleSharp.Text;
using AngleSharp.Xml.Dom;
using AngleSharp.Xml.Parser;
using System;
Expand Down Expand Up @@ -34,25 +38,86 @@ public static IConfiguration WithXml(this IConfiguration configuration)
documentFactory.Register(MimeTypeNames.Svg, LoadSvgAsync);
}

// AngleSharp.Js exposes the DOM extensions of the libraries it finds services of, but
// only sees the parser once it was created (e.g. createDocument would be missing)
if (!configuration.Services.OfType<XmlLibrary>().Any())
{
configuration = configuration.With(XmlLibrary.Instance);
}

return configuration.WithOnly<IXmlParser>(ctx => new XmlParser(ctx));
}

/// <summary>
/// Marks a configuration as using this library.
/// </summary>
private sealed class XmlLibrary
{
public static readonly XmlLibrary Instance = new XmlLibrary();
}

private static Task<IDocument> LoadXmlAsync(IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken)
{
var parser = context.GetService<IXmlParser>() ?? throw new InvalidOperationException("The IXmlParser service has been removed. Cannot continue.");
var document = new XmlDocument(context, options.Source);
document.Setup(options.Response, options.ContentType, options.ImportAncestor);
context.NavigateTo(document);
return parser.ParseDocumentAsync(document, cancellationToken);
return LoadAsync(context, document, options, cancellationToken);
}

private static Task<IDocument> LoadSvgAsync(IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken)
{
var parser = context.GetService<IXmlParser>() ?? throw new InvalidOperationException("The IXmlParser service has been removed. Cannot continue.");
var document = new SvgDocument(context, options.Source);
return LoadAsync(context, document, options, cancellationToken);
}

private static async Task<IDocument> LoadAsync(IBrowsingContext context, Document document, CreateDocumentOptions options, CancellationToken cancellationToken)
{
var parser = context.GetService<IXmlParser>() ?? throw new InvalidOperationException("The IXmlParser service has been removed. Cannot continue.");
document.Setup(options.Response, options.ContentType, options.ImportAncestor);
context.NavigateTo(document);
return parser.ParseDocumentAsync(document, cancellationToken);

await parser.ParseDocumentAsync(document, cancellationToken).ConfigureAwait(false);
await RunScriptsAsync(context, document, cancellationToken).ConfigureAwait(false);
return document;
}

/// <summary>
/// Runs the (inline) scripts of the XHTML elements of a document that was navigated to,
/// in tree order once it has been parsed.
/// </summary>
private static async Task RunScriptsAsync(IBrowsingContext context, Document document, CancellationToken cancellationToken)
{
if (!context.IsScripting())
{
return;
}

var loop = context.GetService<IEventLoop>();
// the parser creates its own elements, so they are found by their name
var scripts = document.Descendants<IElement>()
.Where(m => m.LocalName.Is("script") && m.NamespaceUri.Is(NamespaceNames.HtmlUri) && !m.HasAttribute("src"))
.ToArray();

foreach (var script in scripts)
{
var type = script.GetAttribute("type");
var service = context.GetScripting(String.IsNullOrEmpty(type) ? MimeTypeNames.DefaultJavaScript : type);

if (service is null || script.Parent is null)
{
continue;
}

var response = VirtualResponse.Create(r => r.Address(document.DocumentUri).Content(script.TextContent ?? String.Empty));

try
{
await service.EvaluateScriptAsync(response, new ScriptOptions(document, loop) { Element = script as IHtmlScriptElement }, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// a failing script doesn't stop the others
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
}
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Adds a powerful XML and DTD parser to AngleSharp.</Description>
<Product>AngleSharp.Xml</Product>
<Version>1.3.0</Version>
<Version>1.3.1</Version>
<LangVersion>latest</LangVersion>
<SignAssembly>true</SignAssembly>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
Expand Down
Loading