2010-08-04 19 views
12

Necesito crear un atributo "abc" con el prefijo "xx" para un elemento "aaa". El siguiente código agrega el prefijo pero también agrega el namespaceUri al elemento.Cómo agregar atributos a xml usando XmlDocument en C# .net CF 3.5

salida requerida:

<mybody> 
<aaa xx:abc="ddd"/> 
<mybody/> 

Mi Código:

XmlNode node = doc.SelectSingleNode("//mybody"); 
    XmlElement ele = doc.CreateElement("aaa"); 

    XmlAttribute newAttribute = doc.CreateAttribute("xx","abc",namespace);    
    newAttribute.Value = "ddd"; 

    ele.Attributes.Append(newAttribute); 

    node.InsertBefore(ele, node.LastChild); 

El código anterior genera:

<mybody> 
<aaa xx:abc="ddd" xmlns:xx="http://www.w3.org/1999/XSL/Transform"/> 
<mybody/> 

salida deseada es

<mybody> 
<aaa xx:abc="ddd"/> 
<mybody/> 

y la declaración del atributo "xx" se debe hacer en el nodo raíz como:

<ns:somexml xx:xsi="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://x.y.z.com/Protocol/v1.0"> 

¿Cómo se puede conseguir si la salida en el formato deisred? Si el xml no está en este formato deseado, no se puede procesar más ...

¿Alguien puede ayudar?

Gracias, Vicky

Respuesta

32

creo que es sólo una cuestión de establecer el atributo relevante directamente en el nodo raíz. Aquí está un ejemplo de programa:

using System; 
using System.Globalization; 
using System.Xml; 

class Test 
{ 
    static void Main() 
    { 
     XmlDocument doc = new XmlDocument(); 
     XmlElement root = doc.CreateElement("root"); 

     string ns = "http://sample/namespace"; 
     XmlAttribute nsAttribute = doc.CreateAttribute("xmlns", "xx", 
      "http://www.w3.org/2000/xmlns/"); 
     nsAttribute.Value = ns; 
     root.Attributes.Append(nsAttribute); 

     doc.AppendChild(root); 
     XmlElement child = doc.CreateElement("child"); 
     root.AppendChild(child); 
     XmlAttribute newAttribute = doc.CreateAttribute("xx","abc", ns); 
     newAttribute.Value = "ddd";   
     child.Attributes.Append(newAttribute); 

     doc.Save(Console.Out); 
    } 
} 

Salida:

<?xml version="1.0" encoding="ibm850"?> 
<root xmlns:xx="http://sample/namespace"> 
    <child xx:abc="ddd" /> 
</root> 
Cuestiones relacionadas