Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create XmlElement attributes with prefix?

Tags:

c#

xml

I need to be able to define an attribute with a prefix in a xml element.

For instance...

<nc:Person s:id="ID_Person_01"></nc:Person>

In order to do this I though that the following would have worked.

XmlElement TempElement = XmlDocToRef.CreateElement("nc:Person", "http://niem.gov/niem/niem-core/2.0");
TempElement.SetAttribute("s:id", "http://niem.gov/niem/structures/2.0", "ID_Person_01");

Unfortunately, XmlElement.SetAttribute(string, string, string) does not seem to support parsing the prefix as I receive the error below.

The ':' character, hexadecimal value 0x3A, cannot be included in a name.

How would I define an attribute with prefix?

like image 793
Eddie Avatar asked Feb 12 '10 21:02

Eddie


People also ask

How do you add a prefix in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

What is prefix in XML?

An XML namespace prefix is an abbreviation for the full XML namespace. Because namespaces are meant to differentiate unqualified XML names, it's better that the namespaces themselves be sufficiently long to create a lexically distinct new name when prepended to the unqualified names.

What is the difference between XmlAttribute and XmlElement?

An Attribute is something that is self-contained, i.e., a color, an ID, a name. An Element is something that does or could have attributes of its own or contain other elements.

Which C# component is the XmlElement attribute applied to?

The XmlElementAttribute can be applied multiple times to a field that returns an array of objects. The purpose of this is to specify (through the Type property) different types that can be inserted into the array. For example, the array in the following C# code accepts both strings and integers.


1 Answers

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);
like image 157
Jeff Sternal Avatar answered Nov 03 '22 21:11

Jeff Sternal