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
4 changes: 2 additions & 2 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"version": 1,
"isRoot": true,
"tools": {
"fallout.cli": {
"version": "11.0.18",
"fallout.globaltool": {
"version": "10.4.0",
"commands": [
"fallout"
]
Expand Down
350 changes: 350 additions & 0 deletions AGENTS.md

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
# 1.2.0

Released on Friday, August 21 2026.

- Updated to complete DTD identity and reference validation semantics (#31)
- Improved preservation of CDATA sections as first-class DOM nodes (#30)
- Added the XML-specific `CDATA` factory (#29)
- Added support for XML document metadata (#29)
- Added Canonical XML 1.1 and Exclusive XML Canonicalization 1.0 serialization (#34)
- Added XML Base, `xml:id`, and inherited `xml:lang` convenience semantics (#33)
- Added optional XSD 1.0 document validation with diagnostics (#35)

# 1.1.0

Released on Friday, July 31 2026.
Expand Down
8 changes: 8 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

The guidance is shared with every AI agent working here, so it lives in AGENTS.md and is
imported below. Record new guidance there rather than in this file.

@AGENTS.md
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
[![GitHub Tag](https://img.shields.io/github/tag/AngleSharp/AngleSharp.Xml.svg?style=flat-square)](https://github.com/AngleSharp/AngleSharp.Xml/releases)
[![NuGet Count](https://img.shields.io/nuget/dt/AngleSharp.Xml.svg?style=flat-square)](https://www.nuget.org/packages/AngleSharp.Xml/)
[![Issues Open](https://img.shields.io/github/issues/AngleSharp/AngleSharp.Xml.svg?style=flat-square)](https://github.com/AngleSharp/AngleSharp.Xml/issues)
[![Gitter Chat](http://img.shields.io/badge/gitter-AngleSharp/AngleSharp-blue.svg?style=flat-square)](https://gitter.im/AngleSharp/AngleSharp)
[![StackOverflow Questions](https://img.shields.io/stackexchange/stackoverflow/t/anglesharp.svg?style=flat-square)](https://stackoverflow.com/tags/anglesharp)
[![CLA Assistant](https://cla-assistant.io/readme/badge/AngleSharp/AngleSharp.Xml?style=flat-square)](https://cla-assistant.io/AngleSharp/AngleSharp.Xml)

AngleSharp.Xml extends the core AngleSharp library with some XML capabilities. This repository is the home of the source for the AngleSharp.Xml NuGet package.
Expand Down
4 changes: 1 addition & 3 deletions build/_build.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Fallout.Common" Version="11.0.18" />
<!-- Transitive pin: Fallout.Common 11.0.18 still resolves 10.0.6, which carries advisories. -->
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.10" PrivateAssets="All" />
<PackageReference Include="Fallout.Common" Version="10.4.0" />
</ItemGroup>

</Project>
13 changes: 13 additions & 0 deletions docs/general/02-Capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ AngleSharp.Xml extends the AngleSharp ecosystem with XML-native parsing and seri
- Use AngleSharp DOM interfaces (IDocument, IElement, IAttr, INode)
- Query and update XML nodes with the same API style used in AngleSharp
- Manipulate attributes, text nodes, comments, and processing instructions
- Inspect XML declaration version, encoding, and standalone metadata
- Create and preserve XML CDATA section nodes
- Resolve effective XML Base URIs and URLs
- Normalize and look up live `xml:id` values
- Resolve inherited `xml:lang` values

## Namespace handling

Expand All @@ -29,19 +34,27 @@ AngleSharp.Xml extends the AngleSharp ecosystem with XML-native parsing and seri

- Produces XML documents and SVG documents depending on content type
- Works with XML-oriented workflows in mixed markup processing pipelines
- Validates DTD ID uniqueness and IDREF / IDREFS references
- Validates ENTITY / ENTITIES against declared unparsed entities and notations
- Looks up elements by their DTD-declared ID attributes

## Serialization

- Serialize to XML-oriented output with ToXml
- Use auto-selected formatter behavior with ToMarkup
- Configure empty-element behavior using XmlMarkupFormatter.IsAlwaysSelfClosing
- Serialize documents and rooted element subtrees using Canonical XML 1.1
- Serialize using Exclusive XML Canonicalization 1.0 with inclusive namespace prefixes

## Diagnostics and control

- Suppress parse errors in best-effort scenarios
- Keep source references for analysis or tooling
- Observe element creation positions via callback hooks
- Subscribe to parser lifecycle events (Parsing, Parsed, Error)
- Validate existing documents against one or more XSD 1.0 schemas
- Collect XSD errors and warnings with available source locations
- Resolve trusted schema imports and includes through a configured resolver

## Typical high-value scenarios

Expand Down
16 changes: 13 additions & 3 deletions docs/general/03-Limitations.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@ section: "AngleSharp.Xml"

AngleSharp.Xml is designed for practical XML parsing and DOM workflows in the AngleSharp ecosystem. It is not intended to replace every specialized XML stack.

## Not a full XML schema stack
## XSD validation scope

AngleSharp.Xml does not provide a full XSD validation subsystem. If strict schema validation is required, pair it with dedicated validation tools.
XSD validation targets XML Schema 1.0 through the platform `System.Xml.Schema` engine. XML Schema 1.1 is not supported. Validation operates on the current serialized DOM after parsing, so diagnostic line positions describe that representation rather than necessarily matching the original source after DOM mutations.

External schema imports and includes are disabled by default. A configured resolver should only be enabled for trusted schema locations.

## Query model differences

AngleSharp.Xml is centered on AngleSharp DOM operations and selector-based querying. If your architecture requires XPath-first querying, plan for an additional library.

## Entity reference nodes

AngleSharp's core DOM does not expose entity reference nodes. `IXmlDocument.CreateEntityReference` explicitly throws `NotSupportedException`; entity references encountered while parsing are resolved to replacement text instead.

## Error suppression tradeoff

When IsSuppressingErrors is enabled, malformed input may still produce a DOM, but document structure can be surprising. Treat this as recovery mode, not strict validation mode.
Expand All @@ -22,6 +28,10 @@ When IsSuppressingErrors is enabled, malformed input may still produce a DOM, bu

Serialization behavior depends on the selected formatter. If deterministic output style is important, explicitly choose XmlMarkupFormatter and configure it instead of relying on auto-selection.

## Canonical XML input scope

Canonical serialization operates on the existing AngleSharp DOM and accepts complete documents or rooted element subtrees. It does not accept arbitrary XPath node sets. Canonical output therefore reflects the declarations, entity replacements, and default attributes materialized by the parser; the current partial DTD implementation may not materialize every default required by a validating XML processor.

## Performance and memory

Like other DOM parsers, full-document parsing keeps an in-memory object graph. For very large inputs, consider chunking or stream-first preprocessing before constructing a full DOM.
Expand All @@ -40,6 +50,6 @@ Use AngleSharp.Xml when you want:

Use additional tooling when you need:

- Strict schema validation
- XML Schema 1.1 validation
- XPath-centric querying
- Specialized industry-specific XML validation stacks
116 changes: 116 additions & 0 deletions docs/tutorials/01-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,76 @@ var formatter = new XmlMarkupFormatter
var xml = document.ToHtml(formatter);
```

### Canonical XML

`ToCanonicalXml` produces canonical UTF-8 bytes without a byte-order mark. Canonical XML 1.1 is the default mode.

```cs
var canonicalBytes = document.ToCanonicalXml();
```

Select Exclusive XML Canonicalization 1.0 and its inclusive namespace prefixes through options:

```cs
var options = new XmlCanonicalizationOptions
{
Mode = XmlCanonicalizationMode.ExclusiveXml10,
IncludeComments = true,
InclusiveNamespacePrefixes = new[] { "ds", "#default" },
};

document.ToCanonicalXml(outputStream, options);
```

The stream overload leaves the destination stream open. Both modes remove XML declarations and doctypes, expand empty elements, replace CDATA boundaries with character content, normalize escaping, and order namespace declarations and attributes canonically.

Canonicalization accepts complete documents and rooted element subtrees. Canonical XML 1.1 subtree output carries applicable ancestor namespace, `xml:lang`, `xml:space`, and fixed-up `xml:base` context. Exclusive mode emits visibly used namespaces plus any configured inclusive prefixes.

### XSD validation

Validate an existing document against one or more inline XML Schema 1.0 documents:

```cs
var result = document.ValidateXsd(commonSchema, documentSchema);

if (!result.IsValid)
{
foreach (var diagnostic in result.Diagnostics)
{
Console.WriteLine($"{diagnostic.Severity}: {diagnostic.Message} ({diagnostic.LineNumber}:{diagnostic.LinePosition})");
}
}
```

Validation collects errors and warnings by default. Use options to stop after the first error or suppress warnings:

```cs
var options = new XsdValidationOptions
{
IsFailFast = true,
IsReportingWarnings = false,
};

var result = document.ValidateXsd(schemas, options);
```

For schemas using `xs:include` or `xs:import` with locations, configure a `System.Xml.Schema.XmlSchemaSet` with source URIs and a resolver, then pass it to `ValidateXsd`. External resolution is disabled by default; enable a resolver only for trusted schema locations.

```cs
var schemas = new XmlSchemaSet
{
XmlResolver = new XmlUrlResolver(),
};
schemas.Add(null, schemaPath);

var result = document.ValidateXsd(schemas, new XsdValidationOptions
{
SchemaResolver = new XmlUrlResolver(),
});
```

Diagnostic locations refer to the current serialized DOM used for post-parse validation. A source URI is included when the document or configured schema provides one.

## DOM model and querying

AngleSharp.Xml uses AngleSharp DOM interfaces and works with standard operations:
Expand All @@ -126,6 +196,52 @@ var item = document.QuerySelector("item");
item.SetAttribute("status", "active");
```

### XML namespace semantics

Common attributes from the XML namespace have convenience APIs on elements and documents.

```cs
var item = document.QuerySelector("item");

var effectiveBaseUri = item.GetXmlBaseUri();
var effectiveBaseUrl = item.GetXmlBaseUrl();
var effectiveLanguage = item.GetXmlLanguage();
var xmlId = item.GetXmlId();
var target = document.GetElementByXmlId("chapter-1");
```

`GetXmlBaseUri` resolves inherited `xml:base` values against the document URL and returns non-ASCII LEIRI characters without escaping. `GetXmlBaseUrl` returns AngleSharp's URL representation, whose `Href` is URI-escaped.

`GetXmlLanguage` returns the nearest inherited `xml:lang` value. An empty value resets inherited language information and is returned as an empty string; null means no language was declared.

Parsed `xml:id` values receive ID whitespace normalization. `GetElementByXmlId` searches current DOM state in document order, so attribute mutations are reflected immediately.

### XML declaration metadata

`IXmlDocument` exposes the parsed XML declaration. Documents without a declaration use XML 1.0 defaults and have a null `XmlEncoding`.

```cs
var document = parser.ParseDocument(
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><root />");

Console.WriteLine(document.XmlVersion); // 1.0
Console.WriteLine(document.XmlEncoding); // utf-8
Console.WriteLine(document.XmlStandalone); // true
```

### CDATA sections

Create XML-native CDATA sections through `IXmlDocument`. Parsed CDATA sections are also preserved as `IXmlCDataSection` nodes during DOM transformations and XML serialization.

```cs
var section = document.CreateCDataSection("<unescaped>content</unescaped>");
document.DocumentElement.AppendChild(section);
```

CDATA content cannot contain the closing delimiter `]]>`. Creation and character-data mutations that would introduce it throw `DomException` without changing the section.

AngleSharp's core DOM does not expose entity reference nodes. `CreateEntityReference` therefore throws `NotSupportedException`; parsed entity references continue to be resolved to their replacement text.

## DTD validity signal

When a document contains DOCTYPE declarations, AngleSharp.Xml evaluates DTD-related validity and exposes the result via `document.IsValid`.
Expand Down
18 changes: 17 additions & 1 deletion docs/tutorials/05-DTD-Validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,28 @@ Current DTD-related behavior includes:
- Undeclared attributes are flagged invalid (except namespace declarations)
- #REQUIRED constraints are enforced
- #FIXED constraints are enforced when attribute is present
- ID values are normalized and must be unique across the document
- Each element type may declare at most one ID attribute, with #IMPLIED or #REQUIRED defaults
- IDREF and IDREFS values must resolve to declared IDs, including forward references
- ENTITY and ENTITIES values must name declared unparsed entities
- Unparsed entities and NOTATION attributes must reference declared notations
- Internal general entity replacement in text nodes for declared internal entities
- External subset loading for local file-based SYSTEM identifiers
- Absolute file paths are supported
- Relative paths are resolved against the current process working directory
- External general entity replacement when entities are declared in loaded local external subsets

## DTD ID lookup

DTD-declared IDs can be inspected and looked up after parsing:

```cs
var id = element.GetDtdId();
var target = document.GetElementByDtdId("chapter-1");
```

Lookup reads the current attribute value, so later DOM mutations are reflected immediately. The declared ID attribute metadata is preserved when XML elements are cloned.

## What is currently limited or not supported

You should be aware of these boundaries:
Expand All @@ -92,7 +108,7 @@ You should be aware of these boundaries:
- Full content-model grammar support is incomplete in internal fallback paths
- Complex nested groups and advanced quantifier combinations may not be fully validated
- Attribute default-value materialization from DTD declarations is limited
- XSD validation is not included
- XML Schema 1.0 validation is available separately through `ValidateXsd`

## Recommended usage pattern

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.1.0",
"version": "1.2.0",
"preview": true,
"description": "The doclet for the AngleSharp.Xml documentation.",
"keywords": [
Expand Down
Loading
Loading