# MS Project XML

> Export schedules as MS Project XML, import files written by MS Project and other tools, and read project files on a server without a DOM.

MS Project's XML format is the common exchange format for project schedules: MS Project, ProjectLibre, GanttProject and many PPM tools read and write it. The Gantt exports and imports it without a browser XML parser, so the same code runs in Node and in workers.

## Export

```ts
function downloadProjectXml() {
  const xml = gantt.toMSProjectXML();
  const url = URL.createObjectURL(new Blob([xml], { type: 'application/xml' }));
  const link = document.createElement('a');
  link.href = url;
  link.download = 'warehouse-fit-out.xml';
  link.click();
  URL.revokeObjectURL(url);
}
```

`toMSProjectXML()` writes:

- the project name, start and finish, and the minutes per day and per week from `hoursPerDay` and `daysPerWeek`;
- every calendar with its working days, working hours and exceptions (holidays and working days);
- every task in tree order with its WBS code and outline level, start, finish, duration (in the ISO form MS Project uses, such as `PT40H0M0S`), percent complete, constraint type and date, manual scheduling, task calendar and baselines;
- every link as a predecessor link with its type and lag;
- your task ids in the **Text1** custom field, so a file exported, edited in MS Project and imported again keeps your ids.

Durations are written in the task's own unit, and summaries in days. The project name comes from the `name` of a [headless project](https://docs.birchui.com/gantt/headless.md) or of a loaded JSON or XML document; the widget uses "Project" otherwise.

## Import

```ts
fileInput.addEventListener('change', async () => {
  const file = fileInput.files?.[0];
  if (!file) return;
  try {
    gantt.fromMSProjectXML(await file.text());
  } catch (error) {
    showToast(`${file.name} is not an MS Project XML file.`);
  }
});
```

`fromMSProjectXML(xml)` replaces the current project with the file's tasks, links, calendars, project calendar and working units, reschedules it and clears the undo history. It reads:

| From the file | Into |
| --- | --- |
| Tasks and their outline levels | `tasks` with `parentId` |
| Text1 (when present) or UID | Task `id` |
| Name, Start, Finish, Duration, PercentComplete | `name`, `start`, `end`, `duration`, `percentDone` |
| Milestone, Manual | `type: 'milestone'`, `manuallyScheduled` |
| ConstraintType, ConstraintDate | `constraint` |
| Task calendar | `calendarId` |
| Baselines 0 to 10 | `baselines` |
| Predecessor links with type and lag | `dependencies`, with ids such as `'survey->permit'` |
| Calendars, weekdays and exceptions | `calendars` |
| MinutesPerDay, MinutesPerWeek | `hoursPerDay`, `daysPerWeek` |

The reader is tolerant of real-world files: it accepts namespace prefixes, comments, CDATA sections and slightly broken markup. A link to a task that is not in the file is skipped with one warning per link, and a percentage lag (which the Gantt does not support) is imported as no lag with a warning. Text that is not MS Project XML at all, without a `<Project>` element, throws a `SyntaxError`, so wrap the call when users pick files.

Dates in MS Project XML carry no time zone. They are read and written as wall-clock time in the Gantt's `timeZone`.

### Size limits

The reader refuses a file that is larger than it expects, so a file built to exhaust memory is stopped early.

| Limit | Default | Applies to |
| --- | --- | --- |
| `maxLength` | 67,108,864 (64 MiB of characters) | The length of the XML text |
| `maxTasks` | 250,000 | `<Task>` elements |
| `maxLinks` | 1,000,000 | Dependencies between tasks |

```ts
import { InputLimitError } from '@birchui/gantt';

try {
  gantt.fromMSProjectXML(xml, { limits: { maxTasks: 50_000 } });
} catch (error) {
  if (error instanceof InputLimitError) {
    console.warn(error.code, error.limit, error.actual);
  }
}
```

Pass only the limits you want to change. `Infinity` turns one off. The error's `code` is `'input-too-long'`, `'too-many-tasks'` or `'too-many-links'`. `readMSProjectXML(xml, warn, { limits })` takes the same option, and the defaults are exported as `DEFAULT_MSP_LIMITS`. Elements nested more than 256 levels deep are read as children of the deepest open element.

## Read a file without a Gantt

`readMSProjectXML(xml, warn?)` parses a file into plain project data without scheduling it or touching the DOM. It is the function `fromMSProjectXML` uses, exported for servers, import previews and migrations:

```ts
import { readMSProjectXML } from '@birchui/gantt';

const project = readMSProjectXML(xmlText, (message) => importLog.push(message));
console.info(project.name, project.tasks.length, project.dependencies?.length, project.calendars?.length);
```

The result has the shape of `toJSON()` output (`name`, `projectStart`, `hoursPerDay`, `daysPerWeek`, `calendars`, `calendarId`, `tasks`, `dependencies`), so you can store it, show a preview, or pass it to `fromJSON` or `createGanttProject`.

## What is not exchanged

- **Resources and assignments** are neither exported nor imported. `resourceIds` on tasks stays in your data and in JSON only.
- Your own task fields other than the id, and task colors, are not written to XML. Keep them in your database keyed by task id, or exchange JSON instead.
- Link ids are not kept: imported links get ids from their tasks, such as `'survey->permit'`.

See [Limitations](https://docs.birchui.com/gantt/limitations.md).

## JSON

For storage in your own backend, JSON is simpler and keeps everything, including your own fields:

```ts
const data = gantt.toJSON();
await api.put(`/projects/${projectId}`, data);

gantt.fromJSON(await api.get(`/projects/${projectId}`));
```

`toJSON()` returns `{ name?, projectStart?, calendarId, hoursPerDay, daysPerWeek, calendars, tasks, dependencies }`, with every task's scheduled `start`, `end` and `duration` written back. `fromJSON(data)` accepts the object or its JSON string, throws a `TypeError` when it has no `tasks` array, and clears the undo history.

## Next steps

- [Headless engine](https://docs.birchui.com/gantt/headless.md) to convert and schedule files on a server.
- [Baselines](https://docs.birchui.com/gantt/baselines.md) for comparing against an imported plan.
