To create a web service around an XML document tree, you write an application endpoint that accepts XML, parses it into a tree of nodes in memory, works with the parts you need, and returns a response—usually XML again. The tree is the intermediate model: XML text goes in, a document object model (DOM) comes out, and your service logic reads or edits that tree. The key condition is that the XML must be well-formed before parsing, and it should be validated against a schema whenever untrusted clients can send it.

The term "web service" is loose. It can mean a SOAP service with a WSDL contract, a REST-style HTTP endpoint that exchanges XML bodies, or even a small internal service whose job is to receive and transform XML documents. This guide covers the shared mechanics—designing the tree, exposing the endpoint, parsing safely, validating, and returning responses—then shows where SOAP and REST-style XML services diverge. I'll use concrete request and response shapes you can adapt to Java, Python, .NET, Node.js, or Go, since the concepts map cleanly across all of them.

What "XML document tree" really means in a service

When a parser reads XML, it doesn't leave the data as a flat string. It builds a tree: a document node containing element nodes, each element holding child elements, attributes, and text. That tree is the DOM, and it's the object your service code navigates.

An XML document has exactly one root element. Inside it, elements nest, and each must close in the order it opened. Attributes live on elements and can't repeat within one element. Text content sits inside elements. A small example makes the structure obvious:

The document node wraps order; order has an id attribute and two children (customer and items); items has two item children. Any operation you perform—reading quantity, adding a line, computing a total—walks this tree.

Two parser families matter for service design. A DOM parser builds the whole tree in memory, which makes navigation and modification easy and gives you random access to any node. A streaming parser (SAX, StAX, or similar) reads events and doesn't hold the tree, which is memory-efficient for huge documents but awkward for edits. For a typical web service where payloads are modest—orders, records, configuration fragments—DOM is the practical default; reach for streaming when documents can be tens or hundreds of megabytes.

Prerequisites before you write the service

You need four things settled before code.

First, a definite request and response schema. Decide the root element name, the allowed children, which elements are required, and what data types they carry. Write this down as an XSD (XML Schema Definition) or at least a contract document, because the tree shape is your API.

Second, a runtime or framework that can expose HTTP (or SOAP) and parse XML. Standard libraries exist in every major language: Java's javax.xml packages and JAX-WS/JAX-RS, Python's xml.dom.minidom and xml.etree.ElementTree, .NET's System.Xml, and Node's various XML packages. You generally don't need a heavyweight dependency to parse XML.

Third, a security posture. XML parsers are configurable, and default configurations on some platforms still allow dangerous features like external entity resolution. You must disable external entities and DTD processing for untrusted input unless you have a specific reason to allow them.

Fourth, a decision about transport style: SOAP (envelope, headers, WSDL) or plain XML over HTTP. Both use the same tree mechanics underneath; they differ in contract formality and tooling.

Step 1: Design the document tree as your data contract

Start from the business object, not from code. If the service handles purchase orders, list the fields: order identifier, customer, line items with SKU and quantity, shipping address, total. Then arrange them hierarchically—elements that repeat become children, values that qualify an element become attributes, and derived values (like a computed total) stay out unless the client is meant to send them.

Make repetition explicit with a wrapper element (items containing item children) rather than repeating ungrouped siblings; it's easier to validate and to navigate. Decide which values are attributes versus child elements. A rough rule many teams use: attributes for compact identifiers and metadata, child elements for content and anything that may grow.

Write the XSD now, while the shape is fresh. Here's a minimal schema for the order example:

That schema encodes three guarantees the service can now rely on: id and sku are present, qty is a positive integer, and there's at least one item. Each guarantee removes a manual check from your handler code.

The success check for this step is simple: validate two or three hand-written sample documents against the XSD, including one that should fail. If the failing one passes, the schema is too permissive and your service will inherit that looseness.

Step 2: Expose an HTTP endpoint that accepts XML

A web service needs an address and a method. For a resource that receives documents, a common pattern is POST /orders with the XML body, returning 201 Created and either the stored document or a receipt.

In framework terms, you register a route, read the raw request body as bytes, check the content type (application/xml or text/xml), and hand the bytes to the parser. Don't parse from a string if you can parse from a stream or bytes—it avoids encoding mismatches. XML declares its encoding, and well-behaved parsers honor it.

The order of operations inside the handler matters:

1: Check the content type and reject obvious mismatches early (reversible, cheap check). 2: Enforce a size limit on the body before reading it fully. 3: Parse into a DOM tree. 4: Validate against the XSD. 5: Run business logic against the tree. 6: Serialize a response tree back to XML.

The size limit is a genuine defense: a DOM parser expands the tree in memory, and a maliciously deep or huge document can exhaust the heap. A few megabytes is a reasonable cap for most document services; raise it deliberately if clients legitimately send large files.

Set the endpoint's other HTTP details explicitly. Return 400 Bad Request when parsing fails (malformed XML) and 422 Unprocessable Entity when the XML is well-formed but fails schema validation. That distinction tells clients whether their serializer is broken or their data is. Use 415 Unsupported Media Type when the content type is wrong.

Expect this result: a request with well-formed, schema-valid XML reaches the item-handling code; anything else stops at a specific error status. To check success, send one valid and three broken documents (malformed, missing required attribute, wrong type) and confirm each produces the intended status.

Step 3: Parse safely into a tree

This is where most beginner services break. Default parser settings differ across platforms and versions, and some allow XML External Entity (XXE) processing, which can read local files or trigger network requests. The fix is configuration, and the exact flags depend on your language and parser library, so consult the documentation for the version you're on.

The stable principles, which apply everywhere:

Disable DTD processing entirely if your schema doesn't need it (it usually doesn't). Disable external entity resolution and external schema loading. Disable XInclude. Set limits on entity expansion if internal entities must be allowed (this is the guard against "billion laughs" style expansion).

In Java's DOM implementation, this usually means setting features such as disallowing doctype declarations and turning off external general and parameter entities on the DocumentBuilderFactory before creating the builder. In .NET's XmlReader/XmlDocument path, you set DtdProcessing to prohibit and pass a resolver that returns nothing. Python's xml.etree.ElementTree blocks external entities by default in recent versions, whereas xml.dom.minidom and the SAX modules should be configured deliberately; defusedxml exists precisely to harden these. In Node, choose a maintained XML library and check its entity-handling options rather than assuming.

The verification for this step is concrete: feed the parser a document containing an external entity reference and confirm it either errors or leaves the entity unexpanded. If it resolves the entity, you have an open door.

Once parsing succeeds, keep the tree in a well-typed form for your logic. Many stacks let you map the DOM to generated classes from the XSD (JAXB in Java, xsd.exe-generated types in .NET, similar tools elsewhere). Generated classes reduce string-based navigation bugs, but they add generation steps and sometimes fail awkwardly on schema evolution. For small, stable documents, walking the DOM directly with helper functions is perfectly serviceable.

Step 4: Validate against the schema

Validation is a separate pass from parsing. Parsing answers "is this well-formed?"; validation answers "does it match my contract?" Do both, in that order, and return distinct errors.

A validating parser is configured with the XSD and reports violations with line and column numbers. Surface enough of that detail to be useful without leaking server paths or stack traces. A good error envelope looks like this:

Two design decisions deserve attention here. First, validation is not business validation—schema can enforce "qty is a positive integer" but not "qty may not exceed available stock." Put the latter in handler code after schema validation passes, and return a different error code. Mixing the two makes failures confusing.

Second, treat schema validation as the boundary for trust. Anything past validation can be assumed structurally correct, so your handler reads order/items/item without defensive null checks for missing wrappers. That assumption is the main payoff of writing a real XSD rather than hand-checking fields.

The success check: take a valid document, corrupt exactly one thing (delete a required attribute), and confirm the service returns a schema error naming that attribute, not a generic 500.

Step 5: Work with the tree in your service logic

With a validated tree in hand, the service does its real job—compute, store, transform, or query. Tree operations fall into a few patterns, and naming them helps because frameworks express them differently.

Read by path. Locate a node by walking children or by an XPath expression (/order/items/item[@sku='X-9']/@qty). XPath is concise and expressive for filtering; direct DOM traversal is faster and easier to debug. For a handful of fixed fields, direct traversal with small helper functions usually wins on clarity.

Modify in place. Change an attribute, append a child element, remove a node. This is where DOM shines—your code edits the same structure it will serialize.

Build a response tree. Either clone and trim the request tree, or construct a fresh tree with the response shape. Constructing fresh is safer: you control exactly what goes out and avoid accidentally echoing fields clients shouldn't see.

A worked example clarifies the arithmetic. Suppose the handler must compute each line total as quantity times unit price and set a total on the order. The tree gives you qty as an attribute and unitPrice as a child element of each item. The logic is: for every item node under items, parse qty (already guaranteed positive by schema), read unitPrice (schema types it as decimal), multiply, sum, and set the order's total attribute. If the client sent a total, ignore it—derived values should be server-computed. This is a small but real instance of a broader rule: never trust a client-supplied value that you can compute yourself from validated inputs.

Thread safety deserves a mention. A DOM tree is mutable and not safe to share across threads while being modified. In a request-scoped handler that's a non-issue; in a service that caches parsed trees, either treat them as immutable after construction or clone per request.

Step 6: Serialize and return the response

Serialization takes your tree and writes XML. Configure it deliberately:

Set the encoding (UTF-8 is the safe default) and declare it in the XML declaration. Decide on pretty-printing; human-readable output helps debugging but adds bytes. Many teams pretty-print in development and compact in production, or leave it consistent. Avoid namespace prefixes if you're not using namespaces; if you are, serialize them consistently so clients don't need special handling.

Return the response with the correct Content-Type: application/xml; charset=utf-8. If the response belongs at a new URI (a created order), include a Location header. Pair the body with a meaningful status code: 200 for reads and transforms, 201 for creates.

The check: parse your own response with a fresh parser and validate it against the response XSD if you defined one. Services that never read their own output tend to ship responses their clients can't parse.

SOAP versus plain XML over HTTP: same tree, different packaging

Both styles move an XML document tree across the wire; they differ in ceremony.

A SOAP service wraps your document in an Envelope with a Body (and optionally Header), publishes a WSDL that describes operations and message types, and is typically consumed through generated client stubs. The WSDL is the contract, and generation tools do heavy lifting on both sides—at the cost of complexity, verbose messages, and tooling friction when schemas change.

A plain XML-over-HTTP (sometimes called REST-style XML) service uses ordinary HTTP methods and status codes, and your XSD or documentation is the contract. It's simpler to build and debug—curl and a browser get you most of the way—but clients must do more of their own parsing and error handling.

The tree mechanics don't change: parse, validate, operate, serialize. Choose SOAP when you're integrating with an environment that already mandates it (some enterprise and legacy systems, certain industry profiles) or when you need WS-Security-style standards. Choose plain XML over HTTP for new internal services and simpler integrations. If you're unsure and both sides are under your control, the plain style is usually the lower-friction starting point.

Failure modes and limits worth knowing in advance

A few problems recur, and knowing them up front saves debugging time.

Namespace confusion is the classic one. If your schema uses target namespaces, every element belongs to that namespace, and queries must account for it. A handler that looks for order when the element is {urn:example:orders}order will find nothing and silently return empty results. Decide on namespaces early; if you can avoid them for an internal service, do, because they add friction to every query.

Encoding mismatches arise when the XML declaration says one encoding and the bytes are another. Parse from bytes or streams and let the parser honor the declaration; don't decode to a string yourself and then re-parse.

Deep nesting and recursion can blow the stack in recursive tree walks or in parsers with default depth limits. Flatten where possible, and set parser depth limits explicitly for untrusted input.

Schema evolution breaks clients when you rename or remove elements. Add optional elements for backwards compatibility, version the schema namespace or the endpoint path when you must break, and keep old endpoints alive through a deprecation window. The tree model doesn't protect you here—discipline does.

Large documents hit the DOM's memory cost. If clients can legitimately send very large XML, plan a streaming path for the heavy case rather than raising limits until the server falls over.

A useful habit is a small test suite of documents: one valid, one valid-at-the-edges (minimum and maximum allowed values), and several invalid in different ways. Run it against every change. It catches namespace, validation, and serialization regressions cheaply.

When to hand the design to someone else

The mechanics here are within reach of a competent developer, but certain decisions benefit from a security review before going live: accepting XML from untrusted internet clients, handling documents with DTDs or external schema references, and integrating with systems that mandate specific SOAP or WS-Security profiles. If a penetration test or reviewer flags parser configuration you don't fully understand, treat that as a stop condition and get help before exposing the endpoint. The XML-specific risk area is narrow but real, and it's cheaper to fix at design time than after a breach.

Otherwise, the path is straightforward: design the tree and schema, expose an endpoint, parse safely, validate, operate on the tree, serialize cleanly, and keep a test corpus. Each step has a checkable success condition, so you can confirm the service behaves before clients depend on it.