Writing xml:lang with an XmlWriter


I’ve written in the past about XML & languages, and why you might be interested in being aware of the language associated with text. xml:lang is your friend, as you can tell from these older posts.


Something that is a bit special about xml:lang is that xml is a reserved namespace. From http://www.w3.org/TR/REC-xml-names/#xmlReserved



The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace. It MAY, but need not, be declared, and MUST NOT be bound to any other namespace name. Other prefixes MUST NOT be bound to this namespace name, and it MUST NOT be declared as the default namespace.


Here is the code you can use to write an xml:lang attribute.



XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent =
true;

using
(StringWriter textWriter = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(textWriter, settings))
{
  writer.WriteStartElement(
“e”);

  writer.WriteStartElement(
“t1”);
  writer.WriteAttributeString(
“xml”, “lang”, null, “en-US”);
  writer.WriteString(
“Hello, world!”);
  writer.WriteEndElement();

  writer.WriteStartElement(
“t2”);
  writer.WriteAttributeString(
“xml”, “lang”, null, “es-AR”);
  writer.WriteString(
“¡Hola, mundo!”);
  writer.WriteEndElement();

  writer.WriteEndElement();
  writer.Flush();

  Trace.WriteLine(textWriter.ToString());
}


Here is the traced output.



<?xml version=”1.0″ encoding=”utf-16″?>
<e>
  <t1 xml:lang=”en-US”>Hello, world!</t1>
  <t2 xml:lang=”es-AR”>¡Hola, mundo!</t2>
</e>


Enjoy!

Comments (0)

Skip to main content