How to create XmlElement attributes with prefix?

If you’ve already declared your namespace in the root node, you just need to change the SetAttribute call to use the unprefixed attribute name. So if your root node defines a namespace like this:

<People xmlns:s="http://niem.gov/niem/structures/2.0">

You can do this and the attribute will pick up the prefix you’ve already established:

// no prefix on the first argument - it will be rendered as
// s:id='ID_Person_01'
TempElement.SetAttribute("id", "http://niem.gov/niem/structures/2.0", "ID_Person_01");

If you have not yet declared the namespace (and its prefix), the three-string XmlDocument.CreateAttribute overload will do it for you:

// Adds the declaration to your root node
var attribute = xmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
attribute.InnerText = "ID_Person_01"
TempElement.SetAttributeNode(attribute);

Leave a Comment