2010-02-12 25 views
5

Necesito poder definir un atributo con un prefijo en un elemento xml.Cómo crear atributos XmlElement con prefijo?

Por ejemplo ...

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

Con el fin de hacer esto a pesar de que la siguiente hubiera funcionado.

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

Por desgracia, no parece XmlElement.SetAttribute (cadena, cadena, cadena) para apoyar a analizar el prefijo como reciba el error abajo.

El carácter ':', valor hexadecimal 0x3A, no se puede incluir en un nombre.

¿Cómo definiría un atributo con prefijo?

Respuesta

16

Si ya ha declarado su espacio de nombre en el nodo raíz, solo necesita cambiar la llamada SetAttribute para usar el nombre de atributo no prefijado. Así que si su nodo raíz define un espacio de nombres de la siguiente manera:

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

Usted puede hacer esto y el atributo recogerá el prefijo que ya ha establecido:

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

Si usted todavía no ha declarado la espacio de nombres (y su prefijo), la sobrecarga de tres cuerdas XmlDocument.CreateAttribute lo hará por usted:

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

Este trabajado ya tenía el espacio de nombres en el nodo raíz Sólo tuvo que quitar el prefijo del primer argumento de Método SetAttribute. Gracias! – Eddie

+1

Muy útil. Una cosa pequeña: falta un operador igual/asignación 'XmlAttribute attribute = xmlDocToRef'. –

1

intente crear el atributo directamente y agregarlo al elemento:

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

El método XMLDocument.CreateAttribute puede tomar 3 cadenas: Prefijo especificado, LocalName y NamespaceURI. Luego puede agregar el atributo al elemento. Algo como esto podría funcionar para usted:

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

Desde mi búsqueda siguió llevando conmigo aquí, voy a responder a esto para XElement. No sé si esta solución también es válida para XmlElement, pero con suerte ayudará al menos a otros que utilicen XElement, que terminan aquí.

Basado en this Agregué xml:space="preserve" a todos los nodos de datos en alguna plantilla, antes de buscar y agregar sus contenidos. Es de código extraño OMI (yo preferiría tres parámetros como se muestra arriba, pero hace el trabajo:..

foreach (XElement lElement in root.Descendants(myTag)) 
{ 
     lElement.Add(new XAttribute(root.GetNamespaceOfPrefix("xml") + "space", "preserve")); 
} 
Cuestiones relacionadas