# How to Use Raw XML Access (L3) with XPath for Advanced Operations in OfficeCLI

> Master advanced OfficeCLI operations using raw XML access (L3) and XPath. Directly manipulate OpenXML package parts with raw and raw-set commands for complex changes beyond L1/L2 APIs.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: how-to-guide
- Published: 2026-08-01

---

**OfficeCLI provides raw XML access (L3) through the `raw` and `raw-set` commands, enabling direct manipulation of OpenXML package parts using XPath expressions when high-level (L1/L2) APIs cannot express complex changes.**

OfficeCLI is an open-source command-line tool for automating Microsoft Office documents. Its architecture separates **high-level reads (L1)**, **structured DOM operations (L2)**, and **raw XML fallback (L3)** for advanced scenarios. When you need to update obscure attributes, insert custom elements, or modify package parts that lack dedicated handlers, **raw XML access (L3) with XPath** provides the necessary escape hatch while maintaining the integrity of the OpenXML package.

## The Three-Layer Architecture

OfficeCLI organizes functionality into three distinct layers to balance safety and flexibility:

- **L1 (High-Level)**: Simple read operations like extracting text or metadata.
- **L2 (DOM-Level)**: Structured element operations using dedicated commands for paragraphs, tables, or slides.
- **L3 (Raw XML)**: Direct OpenXML manipulation for edge cases where L2 commands are insufficient.

You should use L3 operations when updating obscure attributes, inserting custom XML elements, or working with document parts that have no dedicated L2 handler.

## Core L3 Commands

The L3 layer exposes two primary commands defined in **[`CommandBuilder.Raw.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Raw.cs)** (lines 12-30 and 60-108).

### Retrieving XML with `raw`

The `raw` command retrieves the raw XML of any document part. It supports path hints like `/document`, `/styles`, or `/slide[1]`, which are resolved internally through `MsysPathHint.Restore`.

For Excel files, you can slice specific rows using `--start` and `--end`, or filter columns with `--cols`.

```bash

# View the raw XML of the first slide in a PowerPoint file

officecli raw deck.pptx '/slide[1]' --json

```

### Modifying XML with `raw-set`

The `raw-set` command applies XPath expressions to modify document parts. It requires `--xpath` and supports seven actions: `append`, `prepend`, `insertbefore`, `insertafter`, `replace`, `remove`, and `setattr`.

The XML fragment to inject is supplied via `--xml`:

```bash
officecli raw-set report.docx '/document' \
  --xpath "//w:body" \
  --action append \
  --xml '<w:p><w:r><w:t>Inserted via raw‑set</w:t></w:r></w:p>' \
  --json

```

## Implementation Details

According to the OfficeCLI source code, the L3 implementation follows a strict pipeline:

1. **Path Resolution**: Commands resolve part paths through `MsysPathHint.Restore`, converting shortcuts like `/document` into actual package part URIs.
2. **Document Opening**: `DocumentHandlerFactory.Open` selects the appropriate format handler (`WordHandler`, `PowerPointHandler`, or `ExcelHandler`).
3. **XPath Execution**: For `raw-set`, handlers load the part as an `XDocument` and apply XPath using `System.Xml.XPath.Extensions`.
4. **Validation**: After modification, the handler validates the file and reports any new validation warnings.

Each format handler implements `RawSet` specifically in its respective file:

- **[`WordHandler.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/WordHandler.cs)**: Handles `.docx` parts including document.xml and styles.xml.
- **[`PowerPointHandler.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/PowerPointHandler.cs)**: Manages `.pptx` slide parts and shape trees.
- **[`ExcelHandler.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/ExcelHandler.cs)**: Processes `.xlsx` worksheet parts with additional support for row/column slicing.

## Practical XPath Operations

### Viewing Raw XML Structure

Inspect the underlying XML before modifying it:

```bash
officecli raw document.docx '/document' --json

```

### Appending Custom Elements

Add XML fragments to specific nodes using the `append` action:

```bash
officecli raw-set report.docx '/document' \
  --xpath "//w:body" \
  --action append \
  --xml '<w:p><w:r><w:t>Custom paragraph</w:t></w:r></w:p>' \
  --json

```

### Removing Elements

Delete all matching elements using the `remove` action:

```bash
officecli raw-set report.docx '/document' \
  --xpath "//w:comment" \
  --action remove \
  --json

```

### Modifying Attributes

Update specific attributes using `setattr` with the `--xml` parameter containing the attribute assignment:

```bash
officecli raw-set deck.pptx '/slide[1]/shape[2]' \
  --xpath "//p:spPr/a:solidFill/a:srgbClr" \
  --action setattr \
  --xml 'val="00FF00"' \
  --json

```

### Working with Relationships

Insert new parts (like charts) and reference them via relationship IDs:

```bash

# Create the part and capture the relationship ID

REL_ID=$(officecli add-part deck.pptx '/' --type chart --json | jq -r '.relId')

# Insert the chart reference into the slide's shape tree

officecli raw-set deck.pptx '/' \
  --xpath "//p:spTree" \
  --action append \
  --xml "<c:chart xmlns:c='http://schemas.openxmlformats.org/drawingml/2006/chart' r:id='${REL_ID}'/>" \
  --json

```

## Summary

- **OfficeCLI** provides three architectural layers, with L3 offering direct OpenXML access when L1/L2 commands are insufficient.
- The **`raw`** command retrieves XML from any document part, with Excel-specific slicing options for rows and columns.
- The **`raw-set`** command modifies XML using XPath expressions and supports seven actions including `append`, `replace`, and `setattr`.
- Implementation resides in **[`CommandBuilder.Raw.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Raw.cs)** and delegates to format-specific handlers using `System.Xml.XPath.Extensions`.
- Always validate documents after raw modifications, as the command bypasses high-level safety checks.

## Frequently Asked Questions

### What is the difference between L2 and L3 operations in OfficeCLI?

L2 operations use structured DOM commands that understand document semantics (like "add a paragraph" or "insert a table"), while L3 operations provide **raw XML access** that manipulates the underlying OpenXML directly using XPath. Use L2 for standard editing tasks and L3 only when you need to modify attributes or elements that lack dedicated L2 handlers.

### Which XPath actions are supported by the `raw-set` command?

The `raw-set` command supports seven actions: `append` (adds XML as the last child), `prepend` (adds as first child), `insertbefore` (siblings before the match), `insertafter` (siblings after the match), `replace` (substitutes the matched node), `remove` (deletes matched nodes), and `setattr` (sets attributes on matched elements).

### How does OfficeCLI handle XML validation after raw modifications?

After executing `raw-set`, the format-specific handler (`WordHandler`, `PowerPointHandler`, or `ExcelHandler`) validates the modified document using the OpenXML SDK validation rules. Any new validation warnings are reported in the command output, helping you catch schema violations that might corrupt the document in Microsoft Office applications.

### Can I use raw XML access on Excel files with row slicing?

Yes. The **`raw`** command for Excel supports `--start` and `--end` parameters to slice specific row ranges, and `--cols` to filter columns when viewing worksheet XML. However, `raw-set` operations apply to the full XML part regardless of these slicing options, which are only available for the read operation.