---
schema_version: "1"
id: e30b055bd9352342ec26a889123643f5f205b1fcd61f656f068a0d11635c3044
title: Using XML Validator Library Functions
collection: mulesoft
version: current
locale: en-us
portal_url: https://docs.salesforce.com/mulesoft/current/en-us/pdk/latest/policies-pdk-configure-features-xml-validator.md
canonical_url: https://docs.mulesoft.com/pdk/latest/policies-pdk-configure-features-xml-validator
source_site: docs.mulesoft.com
content_type: documentation
content_hash: 4c91be5ce6f264ab73e264e8190dd29cb0a5442a818e22ecc88261662a56127b
description: MuleSoft Documentation Site
release: "1.10"
latest: true
---
---
product: Omni Gateway Policy Development Kit (PDK)
version: 1.10
is-latest-version: true
---

# Using XML Validator Library Functions

> For the full documentation index, see: https://docs.mulesoft.com/llms.txt

> [!NOTE] To view an example policy project that uses Omni Gateway Policy Development Kit (PDK)’s
> XML Validator library, see
> [XML Validation Policy Example](https://github.com/mulesoft/pdk-custom-policy-examples/blob/1.10.0/xml-validation/README.md).

Excessive element counts, nesting depth, and attribute sizes in XML payloads can cause parsers to
consume excessive memory or CPU. The PDK XML Validator library streams the incoming XML body and
enforces configurable limits on its structure and size. Use this library to build custom policies.
The library mirrors the limits of the built-in
[XML Threat Protection Policy](https://docs.mulesoft.com/gateway/latest/policies-included-xml-threat-protection) for
Omni Gateway.

Use the library when your custom policy must perform these tasks.

- Accept XML request or response bodies and reject malformed or oversized documents before the
  gateway fully buffers them.

- Apply limits that match your API’s threat model, such as maximum element depth, number of children
  per element, or text node length.

- Process large bodies incrementally by using the
  [streaming body state](https://docs.mulesoft.com/pdk/latest/policies-pdk-configure-features-headers#streaming-bodies).

> [!NOTE] The XML Validator library is gated behind a Cargo feature and is enabled by default. To
> disable XML Validator features for your policy, see
> [Configure PDK Features in Cargo.toml](https://docs.mulesoft.com/pdk/latest/policies-pdk-create-project#configure-pdk-features).

Import the builder from the `xml_validator` module of the PDK crate.

```Rust
use pdk::xml_validator::XmlValidatorBuilder;
```

## Build an XML Validator

Create a validator with `XmlValidatorBuilder::new()`, chain the configuration methods for the limits
you need, and call `build()`.

The builder methods map to the same constraint types as
[XML Threat Protection Policy](https://docs.mulesoft.com/gateway/latest/policies-included-xml-threat-protection). Names
differ slightly from the policy UI parameters, but the intent matches.

<table><colgroup><col> <col></colgroup><thead><tr><th>Method</th><th>Description</th></tr></thead><tbody><tr><td><div><div><p><code>with_max_depth</code></p></div></div></td><td><div><div><p>Maximum nesting depth of elements in the document.</p></div></div></td></tr><tr><td><div><div><p><code>with_max_attribute_count</code></p></div></div></td><td><div><div><p>Maximum number of attributes on a single element.</p></div></div></td></tr><tr><td><div><div><p><code>with_max_child_count</code></p></div></div></td><td><div><div><p>Maximum number of child nodes of a single element.</p></div></div></td></tr><tr><td><div><div><p><code>with_max_text_length</code></p></div></div></td><td><div><div><p>Maximum length of text node content, as UTF-8 byte length.</p></div></div></td></tr><tr><td><div><div><p><code>with_max_attribute_length</code></p></div></div></td><td><div><div><p>Maximum length of a single attribute value, as UTF-8 byte length.</p></div></div></td></tr><tr><td><div><div><p><code>with_max_comment_length</code></p></div></div></td><td><div><div><p>Maximum length of comment content, as UTF-8 byte length.</p></div></div></td></tr></tbody></table>

If you omit a `with_*` method, that limit isn’t applied, so there’s no restriction on that field.
Call only the methods for limits you want enforced. For type details and any extra options, see the
PDK Rust API documentation for your release.

## Validate an XML Request Body Stream

Validate the raw byte stream of the body. Use the streaming body state so the parser processes data
as it arrives. Streaming is required for bodies larger than the buffered body limit, and it matches
how the PDK exposes large payloads. For more information, see
[Streaming Bodies](https://docs.mulesoft.com/pdk/latest/policies-pdk-configure-features-headers#streaming-bodies).

The `validate_stream` method consumes the stream, succeeds if the document is well-formed and within
your limits, and returns an error if the XML is invalid or breaks a constraint.

```Rust
use anyhow::Result;
use pdk::hl::*;
use pdk::xml_validator::XmlValidatorBuilder;

async fn request_filter(state: RequestState) -> Flow<()> {
    let headers_state = state.into_headers_state().await;

    if !headers_state.contains_body() {
        return Flow::Continue(());
    }

    let body_stream_state = headers_state.into_body_stream_state().await;
    let validator = XmlValidatorBuilder::new()
        .with_max_depth(10)
        .with_max_attribute_count(10)
        .with_max_child_count(50)
        .with_max_text_length(1024)
        .with_max_attribute_length(256)
        .with_max_comment_length(1024)
        .build();

    match validator.validate_stream(body_stream_state.stream()).await {
        Ok(()) => Flow::Continue(()),
        Err(_) => Flow::Break(Response::new(400).with_body("Invalid or disallowed XML payload")),
    }
}

#[entrypoint]
async fn configure(launcher: Launcher, Configuration(_configuration): Configuration) -> Result<()> {
    launcher
        .launch(on_request(|request| request_filter(request)))
        .await?;
    Ok(())
}
```

On success, the example continues the request to run upstream processing. On failure, the policy
returns `400 Bad Request`. Change the status code and body to match your API’s contract.

## Initialize the Validator from Policy Configuration

If you supply limits through your policy schema in GCL, parse the configuration and build the
XmlValidatorBuilder in the #\[entrypoint\] function. If the configuration is invalid or
incompatible, applying the policy fails before traffic reaches the API. Pass the validator into your
request filter. For example, if you need shared ownership across closures, wrap the validator in
std::rc::Rc or std::sync::Arc, depending on your policy layout.

Map your generated config::Config fields to the builder methods in
[Build an XML Validator](#build-xml-validator). Use the types the PDK API expects for your release.

## Interpret Validation Errors

If `validate_stream` returns `Err`, reject the payload. The XML might be malformed or violate a
configured limit. If you need operational detail, log the error at the debug or warn level. If you
can’t expose parser details, return a generic client-facing message.

## See Also

- [Implementing Your Custom Policy Features in Rust](https://docs.mulesoft.com/pdk/latest/policies-pdk-configure-features)

- [Streaming Bodies](https://docs.mulesoft.com/pdk/latest/policies-pdk-configure-features-headers#streaming-bodies)

- [XML Threat Protection Policy](https://docs.mulesoft.com/gateway/latest/policies-included-xml-threat-protection)
