How to Perform Raw XML Access and Manipulation in OfficeCLI: A Complete Guide
OfficeCLI exposes a low-level raw layer through the raw and raw-set CLI commands and the IDocumentHandler interface, enabling direct reading and editing of underlying OpenXML markup via XPath operations.
OfficeCLI is an open-source command-line tool for manipulating Microsoft Office documents programmatically. While high-level APIs handle common tasks, the library’s raw XML access and manipulation capabilities provide surgical precision for advanced scenarios requiring direct interaction with document parts, styles, and relationships.
Architecture of the Raw Layer
The raw functionality is implemented across a three-layer architecture (semantic → query → raw) with three primary components:
CLI Command Definitions
The entry points are defined in [CommandBuilder.Raw.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Raw.cs):
BuildRawCommand(lines 23–55) parses arguments (file,part,--start,--end,--cols) and invokesIDocumentHandler.Raw.BuildRawSetCommand(lines 60–108) parsesxpath,action, and optional--xmlparameters before callingIDocumentHandler.RawSet.
Handler Interface Contract
All document handlers implement [IDocumentHandler.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/IDocumentHandler.cs), which declares the raw layer methods at lines 99–101:
string Raw(string partPath, int? startRow = null, int? endRow = null, HashSet<string>? cols = null);
void RawSet(string partPath, string xpath, string action, string? xml);
Concrete Implementations
The heavy lifting resides in type-specific handlers like [WordHandler.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Handlers/WordHandler.cs):
Raw(lines 69–71) selects a document part and returns itsOuterXml.RawSetinterprets the action string and routes requests through fast-path optimizations or falls back to [RawXmlHelper.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/RawXmlHelper.cs) for general XPath execution.
Reading Raw XML via CLI
Use the raw command to extract OpenXML markup from any document part.
# View the main document XML
officecli raw mydoc.docx /document
# Extract a slice of an Excel worksheet (rows 5-10)
officecli raw mybook.xlsx /Sheet1 --start 5 --end 10
# View specific columns from a sheet
officecli raw data.xlsx /Sheet1 --cols "A,C,E"
The command routes through BuildRawCommand in CommandBuilder.Raw.cs, which validates the part path and delegates to the handler’s Raw method.
Modifying XML with raw-set
The raw-set command enables surgical modifications using XPath selectors and action verbs.
# Replace a style definition
officecli raw-set mydoc.docx /styles \
--xpath "//w:style[@w:styleId='MyStyle']" \
--action replace \
--xml '<w:style w:styleId="MyStyle" w:type="paragraph"><w:name w:val="MyStyle"/></w:style>'
# Append a paragraph to the document body
officecli raw-set mydoc.docx /document \
--xpath "/w:document/w:body" \
--action append \
--xml '<w:p><w:r><w:t>Hello, world!</w:t></w:r></w:p>'
According to the source in WordHandler.cs, the RawSet method handles several action types:
- Special actions like
embed-binary(lines 85–89) - Whole-part replacement for docProps parts
- Fast-path shortcuts for common O(1) operations (single style replacement, paragraph insertion before
sectPr) - General case execution via
RawXmlHelper.Executewhen optimizations don’t apply
Programmatic Access with C#
For integration into .NET applications, use the IDocumentHandler interface directly via DocumentHandlerFactory.
using OfficeCli.Core;
using OfficeCli.Handlers;
// Open document for editing
using var handler = DocumentHandlerFactory.Open("mydoc.docx", editable: true);
// Read raw XML from the styles part
string rawStyles = handler.Raw("/styles");
Console.WriteLine(rawStyles);
// Modify using XPath
string xpath = "//w:style[@w:styleId='MyStyle']";
string newXml = @"<w:style w:styleId='MyStyle' w:type='paragraph'>
<w:name w:val='MyStyle'/>
</w:style>";
handler.RawSet("/styles", xpath, "replace", newXml);
handler.Save();
This approach maps directly to the interface defined in IDocumentHandler.cs and provides the same validation and error-reporting as the CLI.
Advanced: Binary Embedding
The raw layer supports embedding binary data through the embed-binary action, handled specifically in WordHandler.RawSet.
string binaryData = "data:image/png;base64,iVBORw0KGgoAAAANS...";
handler.RawSet("/fontTable",
"/w:font[@w:name='CustomFont']/w:embed",
"embed-binary",
binaryData);
This creates the appropriate ImagePart and updates relationship IDs automatically.
Summary
- Raw XML access in OfficeCLI is implemented through the
raw(read) andraw-set(modify) CLI commands defined inCommandBuilder.Raw.cs. - The handler contract in
IDocumentHandler.csdeclaresRawandRawSetmethods that all document types implement. - Concrete handlers like
WordHandler.csprovide optimized fast paths for common operations while falling back toRawXmlHelper.csfor complex XPath mutations. - Both CLI and programmatic APIs support XPath-based targeting, row/column filtering for Excel, and binary embedding for advanced document manipulation.
Frequently Asked Questions
What is the difference between the raw and raw-set commands in OfficeCLI?
The raw command is read-only and returns the XML string of a specified document part, with optional slicing parameters for Excel rows. The raw-set command performs mutations by accepting an XPath selector, an action (such as replace or append), and new XML content, routing through IDocumentHandler.RawSet.
Which file contains the actual XML manipulation logic for Word documents?
[WordHandler.cs](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Handlers/WordHandler.cs) contains the concrete implementation, including fast-path optimizations for common operations and special handling for actions like embed-binary (lines 85–89).
How does OfficeCLI handle binary data embedding in XML parts?
When the action parameter is set to embed-binary, WordHandler.RawSet invokes RawEmbedBinary to create the appropriate ImagePart, manage relationship IDs, and update the target XML node with the correct reference, accepting base64-encoded data URIs.
Can I filter specific rows when reading raw XML from Excel files?
Yes. The Raw method accepts optional startRow and endRow parameters accessible via the --start and --end CLI flags, allowing you to extract slices of large worksheets without loading the entire XML into memory.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →