How to create XmlElement attributes with a prefix?

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

For instance...

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

To do this, I could work.

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 it receives the error below.

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

How can I define an attribute with a prefix?

+5
source share
4 answers

If you have already declared your namespace in the root of the node, you just need to change the call SetAttributeto use the unprefixed attribute name. Therefore, if your root node defines a namespace like this:

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

, , :

// 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");

( ), XmlDocument.CreateAttribute :

// 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);
+16

XMLDocument.CreateAttribute 3 : , LocalName NamespaceURI. . - :

XmlAttribute newAttribute = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
TempElement.Attributes.Append(newAttribute):
+2

:

XmlAttribute attr = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
attr.InnerText = "ID_Person_01";
TempElement.Attributes.Append(attr);
+1

As my search continued to take me here, I will answer for it XElement. I don’t know if this solution is suitable for XmlElement, but I hope it will at least help others using the XElementones that get here.

Based on this, I added xml:space="preserve"to all the data nodes in a template before looking at and adding their contents. This is a weird IMO code (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"));
 }
0
source

All Articles