---
title: "Load phone number metadata from XML in C#"
url: https://recursiveai.org/onecontact/cookbook/load-custom-phone-number-metadata/
description: "Load a local numbering-rules XML file into OneContact, then parse and format a phone number with your own numbering rules in C#."
version: "1.0.0"
---

# Load phone number metadata from XML in C#

**OneContact** is a free, open-source contact data library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies, no network access.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneContact) · [GitHub](https://github.com/recursive-ai-oss/onecontact-csharp) · [Docs](https://recursiveai.org/onecontact/docs/) · [Download example (.zip)](https://recursiveai.org/onecontact/cookbook/load-custom-phone-number-metadata/load-custom-phone-number-metadata.zip)

Pass `rules.xml` from the zip to `PhoneMetadata.LoadXml`. The XML holds numbering patterns and formats for each territory, not contacts.

```shell
dotnet add package RecursiveAI.OneContact
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using System.Buffers;
using RecursiveAI.OneContact;
using RecursiveAI.OneContact.Phones;

using var xml = File.OpenRead("rules.xml");
var rules = PhoneMetadata.LoadXml(xml);
var parser = new PhoneNumberParser(rules);
var status = parser.TryParse(
    "2025550123", Region.US, false,
    out var phone, out var detail);
if (status != OperationStatus.Done)
    throw new FormatException(
        detail.PrimaryReason.ToString());
Console.WriteLine(phone.IsValid);
var format = PhoneFormat.National;
Console.WriteLine(phone.Format(format));
```

Unzip [the example](https://recursiveai.org/onecontact/cookbook/load-custom-phone-number-metadata/load-custom-phone-number-metadata.zip), then `dotnet run`.

Prints:

```text
True
202.555.0123
```



Put this `rules.xml` next to the project file. The fixture accepts `202-555-0100` through `202-555-0199` as fixed-line numbers and formats the digits with dots. It is a test fixture, not a replacement for the full US numbering plan.

```xml
<phoneNumberMetadata>
  <territories>
    <territory id="US" countryCode="1" internationalPrefix="011">
      <availableFormats>
        <numberFormat pattern="(\d{3})(\d{3})(\d{4})">
          <format>$1.$2.$3</format>
        </numberFormat>
      </availableFormats>
      <generalDesc>
        <nationalNumberPattern>20255501\d{2}</nationalNumberPattern>
      </generalDesc>
      <fixedLine>
        <possibleLengths national="10"/>
        <nationalNumberPattern>20255501\d{2}</nationalNumberPattern>
      </fixedLine>
    </territory>
  </territories>
</phoneNumberMetadata>
```

`LoadXml` throws `InvalidDataException` for malformed XML or data that exceeds its limits. Parsing returns a status and a reason; a successful parse is separate from `phone.IsValid`, which checks the number against the loaded rules.

## Variations

**Read XML you already have as a string.** Replace the `File.OpenRead` line with the following. The rest of the program is unchanged and prints the same result:

```csharp
var text = File.ReadAllText("rules.xml");
using var xml = new MemoryStream(
    System.Text.Encoding.UTF8.GetBytes(text));
```

## Related recipes

- [Parse a phone number](https://recursiveai.org/onecontact/cookbook/parse-phone-number/)
- [Validate a phone number](https://recursiveai.org/onecontact/cookbook/validate-phone-number/)

## The short answer

Open the XML as a stream and pass it to `PhoneMetadata.LoadXml`. Give the result to `new PhoneNumberParser(rules)`, then call that parser’s `TryParse` instead of the static `PhoneNumber.Parse`. The custom parser uses the supplied numbering rules; it doesn’t install them as your app’s default.

## How do you read a phone metadata XML file from a path in C#?

The loader uses Google libphonenumber’s `PhoneNumberMetadata.xml` schema. OneContact 1.0.0 loads the [full upstream file pinned for that release](https://github.com/google/libphonenumber/blob/86ea33cee5c22ab7e23b3de368e7cc7fa439a2b7/resources/PhoneNumberMetadata.xml) as-is. Open it with `File.OpenRead` and pass the stream to `PhoneMetadata.LoadXml`. In the sample, `territory` gives the region and its calling code, `nationalNumberPattern` describes numbers the parser can recognize as valid, and `numberFormat` tells the formatter how to group the digits. The three captured groups become `$1`, `$2`, and `$3` in the dotted output.

Load the rules once and reuse the parser instead of reopening the file for each number. The [phone metadata loader](https://recursiveai.org/onecontact/docs/phones/) compiles the patterns when it loads and ignores the document type definition. It limits the input to 32 million characters, 4,096 territories, and 64 levels of element nesting. Catch `InvalidDataException` if you need to report a bad rules file at startup. File-opening errors come from `File.OpenRead`, before OneContact sees a stream.

## How do you parse XML into a phone number parser without changing the default rules?

Keep a custom `PhoneNumberParser` wherever your app needs the custom rules, such as a test for a specific numbering policy. A number it returns keeps those rules for formatting and validity. The fixture is the parser’s metadata, not a supplement to the built-in data. A number in a calling-code area missing from the file can therefore fail to parse instead of falling back to the default rules.

If you save the result as JSON, don’t expect the rules to travel with the number. [OneContact reads phone JSON using the built-in metadata](https://recursiveai.org/onecontact/docs/phones/). To keep the same policy on reload, persist the input you need and parse it again with your configured parser.
