Metadata-Version: 2.4
Name: pyuppsala
Version: 0.13.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Text Processing :: Markup :: XML
License-File: LICENSE
Summary: Python bindings for the Uppsala XML library
License-Expression: BSD-2-Clause
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://pyuppsala.readthedocs.org/
Project-URL: Repository, https://github.com/kushaldas/pyuppsala

# pyuppsala

Python bindings for the [Uppsala](https://crates.io/crates/uppsala) XML library
-- a zero-dependency, pure-Rust implementation of XML 1.0, Namespaces, XPath
1.0, and XSD validation.

pyuppsala gives you a fast, correct, and memory-safe XML toolkit from Python
with no C dependencies to compile and no transitive native libraries to audit.

This release is against `0.11.0` of Uppsala library.

## Features

- **XML 1.0 parsing** with full well-formedness checking
- **Namespace-aware DOM** with tree mutation (create, append, insert, remove, detach)
- **XPath 1.0** evaluation (all axes, functions, predicates)
- **XSD validation** (structures + datatypes, 40+ built-in types, facets, complex types)
- **XSD regex** pattern matching (Unicode categories, blocks, character class subtraction)
- **XSLT 1.0** transforms with bounded template recursion
- **Imperative XML builder** (`XmlWriter`) for constructing output without a DOM
- **Serialization** with pretty-printing, compact output, and streaming to files
- **Automatic encoding detection** for UTF-8 and UTF-16 (LE/BE)
- **lxml.etree-compatible API** via `pyuppsala.etree`, a near drop-in for much of
  `lxml.etree` backed by Uppsala's secure parser
- **Native batch and fast etree paths** for parsing many documents and running
  simple large-tree aggregates without one Python object per matched node

Read the [full documentation](https://pyuppsala.rtfd.io)

## Security defaults

pyuppsala keeps the main XML attack classes bounded by default:

- Parser resource caps are enabled by default for element depth, entity
  expansion size, and entity-reference nesting.
- DTDs and entity declarations are accepted by default for compatibility, but
  entity expansion is capped. Use `forbid_dtd=True` or `forbid_entities=True`
  when parsing untrusted XML that should not contain DTDs or entity
  declarations.
- XPath evaluation is capped by expression depth and by a per-evaluation node
  visit budget. Do not let untrusted callers choose `max_depth` or
  `max_node_visits`.
- XSD regex matching has group-depth and backtracking-step limits. Do not let
  untrusted callers raise `max_steps`.
- XSLT template recursion is capped by default. Treat stylesheets as trusted
  application configuration; EXSLT compatibility is enabled by default.
- `Document` mutators reject `Node` handles from another document. Use
  `Document.import_subtree()` for intentional cross-document copies.
- `pyuppsala.etree` keeps parser caps on by default. `huge_tree=True` lifts
  those caps for lxml compatibility and should only be used with trusted XML.
- XInclude processing is explicit. Remote includes require
  `network_access=True`; local includes are restricted to the including
  document's base directory and are size-limited.
 - Native fetch helpers (available only in builds with the default-on `net`
   feature; gate use on `pyuppsala._HAS_NET`) cap response bodies at 128 MiB by
   default, including `file://` reads, and keep TLS verification enabled by
   default. Apply your own URL allowlist before fetching attacker-controlled
   URLs.

See the [resource limits and hardening guide](https://pyuppsala.rtfd.io/en/latest/examples.html#resource-limits-and-hardening)
and the [API security notes](https://pyuppsala.rtfd.io/en/latest/api.html#security-defaults-and-boundaries)
for all knobs and default values.

## Installation

```bash
python3 -m pip install pyuppsala
```

Or with [uv](https://docs.astral.sh/uv/):

```bash
uv add pyuppsala
```

Wheels are compiled from Rust via [maturin](https://www.maturin.rs/).
Python 3.10+ is required.

## Quick start

### Parse and query

```python
from pyuppsala import Document, XPathEvaluator

doc = Document("<bookstore><book><title>Moby Dick</title></book></bookstore>")
doc.prepare_xpath()

xpath = XPathEvaluator()
title = xpath.evaluate(doc, "string(//title)")
print(title)  # "Moby Dick"
```

### Build XML

```python
from pyuppsala import XmlWriter

w = XmlWriter()
w.write_declaration()
w.start_element("catalog", [("xmlns", "urn:example")])
w.start_element("item", [("id", "1")])
w.text("Widget")
w.end_element("item")
w.end_element("catalog")
print(w.to_string())
```

### Validate against an XSD schema

```python
from pyuppsala import XsdValidator

schema = """\
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="greeting" type="xs:string"/>
</xs:schema>
"""

validator = XsdValidator(schema)
print(validator.is_valid_str("<greeting>Hello!</greeting>"))  # True
print(validator.is_valid_str("<greeting><bad/></greeting>"))  # False
```

For an existing DOM, `validator.validate(doc)` avoids reparsing XML.
`validator.validate_node(node)` validates a selected element independently
without serializing: it reads document roots directly when no namespace
adjustment is needed and otherwise copies the selected subtree in Rust. Copies
preserve inherited namespace bindings and apply effective default namespaces to
bare element names, matching etree serialization without mutating the source.
It returns validation errors and releases the GIL.

The etree `schema.validate(tree)`, `schema.assertValid(tree)`, `schema.assert_`
and callable schema APIs use this native path; `schema.validate_serialized(tree)`
keeps the serialize-and-reparse behaviour for callers that want to validate
exactly what `tostring` would emit. The 0.12 opt-in names
(`experimental_validate_node`, `experimental_validate`,
`experimental_assertValid`) remain as aliases.

### Mutate the DOM

```python
from pyuppsala import Document

doc = Document("<root><a/></root>")
root = doc.document_element
b = doc.create_element("b")
doc.append_child(root, b)
print(doc.to_xml())  # <root><a/><b/></root>
```

### XSD regex

```python
from pyuppsala import XsdRegex

regex = XsdRegex(r"[0-9]{5}")
print(regex.is_match("12345"))  # True
print(regex.is_match("abcde"))  # False
```

### lxml-compatible etree API

Code written for `lxml.etree` runs after swapping the import. Elements are live
views over the underlying document, with stable identity and the familiar
`.text`/`.tail`/`.attrib` model.

```python
from pyuppsala import etree  # instead of: from lxml import etree

root = etree.fromstring("<catalog><book id='1'>Dune</book></catalog>")
print(root.find("book").text)        # Dune
print(root[0].get("id"))             # 1

cat = etree.Element("catalog")
book = etree.SubElement(cat, "book", {"id": "2"})
book.text = "Neuromancer"
print(etree.tostring(cat, encoding="unicode"))
# <catalog><book id="2">Neuromancer</book></catalog>
```

See the [etree documentation](https://pyuppsala.rtfd.io/en/latest/etree.html)
for the supported and unsupported feature matrix.

## API overview

| Class / function | Purpose |
|---|---|
| `Document(xml)` | Parse XML string into a DOM |
| `Document.from_bytes(data)` | Parse XML bytes (auto-detects UTF-8/UTF-16) |
| `Document.empty()` | Create an empty document for building from scratch |
| `Node` | A handle to a node in the document tree |
| `QName` | A qualified XML name (local name + optional namespace + prefix) |
| `Attribute` | An XML attribute (name + value) |
| `XPathEvaluator` | Evaluate XPath 1.0 expressions |
| `XsdValidator(schema)` | Validate documents against an XSD schema |
| `XmlWriter` | Imperative XML builder (no DOM needed) |
| `XsdRegex(pattern)` | XSD regular expression pattern matcher |
| `Xslt(stylesheet_xml)` | Compile and apply XSLT 1.0 stylesheets |
| `parse(xml)` | Module-level shorthand for `Document(xml)` |
| `parse_bytes(data)` | Module-level shorthand for `Document.from_bytes(data)` |
| `parse_many(items)` | Parse many XML strings or byte strings in native worker threads |
| `fetch_many(urls)` | Fetch many HTTP(S) or file URLs with body limits and per-item results (requires `pyuppsala._HAS_NET`) |
| `fetch_and_parse_many(urls)` | Fetch many URLs and parse each response as XML (requires `pyuppsala._HAS_NET`) |
| `pyuppsala.etree` | lxml.etree-compatible API (`Element`, `SubElement`, `fromstring`, `tostring`, `find`/`findall`, `XPath`, `XMLSchema`, ...) |
| `etree.fromstring_many(items)` | Parse many documents into etree roots with per-item errors |
| `_Element.fast_*()` | Native count/existence/attribute/text-group scans for large etree subtrees |

### Exceptions

| Exception | Raised when |
|---|---|
| `XmlParseError` | XML is syntactically malformed |
| `XmlWellFormednessError` | XML violates well-formedness constraints |
| `XmlNamespaceError` | Namespace prefix is undeclared or misused |
| `XPathError` | XPath expression is invalid |
| `XsdValidationError` | XSD schema itself is invalid |

All exceptions inherit from `Exception`.

## Type stubs

Type stubs (`pyuppsala/__init__.pyi` and `pyuppsala/etree.pyi`, marked with
`py.typed`) ship with the package for full IDE auto-completion and type-checking
with mypy/pyright.

## Development

Builds use Uppsala 0.11.0 from crates.io, including the XSLT parameter and
reserved `xml` namespace fixes. A sibling Uppsala checkout is not required.

```bash
# Clone the repository
git clone https://github.com/kushaldas/pyuppsala.git
cd pyuppsala

# Set up the environment with uv
uv sync

# Build the native extension in development mode
uv run maturin develop

# Run the test suite
uv run pytest

# Build a release wheel
uv run maturin build --release
```

## License

BSD-2-Clause

