Alex Rivera | Logout

How to create XmlElement attributes with prefix?

Asked 2010-02-12T21:42:10.717
15

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?

Edit
Report

1 Answer

0

Since my search kept taking me here, I'll answer this for XElement. I don't know if this solution is also valid for XmlElement, but it will hopefully at least help others using XElement, who end up here.

Based on this I added xml:space="preserve" to all data-nodes in some template, before looking up and adding their contents. It's weird code IMO (I would prefer three parameters as shown above, but it does the job:

 foreach (XElement lElement in root.Descendants(myTag))
 {
      lElement.Add(new XAttribute(root.GetNamespaceOfPrefix("xml") + "space", "preserve"));
 }
answered 2011-08-05T08:07:02.847

Your Answer