2010-08-04 7 views
12

Ich muss ein Attribut "abc" mit dem Präfix "xx" für ein Element "aaa" erstellen. Der folgende Code fügt das Präfix hinzu, fügt dem Element aber auch den namespaceUri hinzu.Wie man Attribute zu Xml mit XmlDocument in C# hinzufügen. NET CF 3.5

Erforderliche Leistung:

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

Mein Code:

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

Der obige Code erzeugt:

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

Wunsch Ausgang

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

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

Wie kann, wenn bekommen die Ausgabe im deisred Format:

Und die Erklärung des „xx“ Attribut sollte wie in den Wurzelknoten durchgeführt werden? Wenn das XML nicht in diesem gewünschten Format ist, kann es nicht mehr verarbeitet werden.

Kann jemand helfen?

Danke, Vicky

Antwort

32

Ich glaube, es ist nur eine Frage der relevanten Attribut direkt auf dem Wurzelknoten zu setzen. Hier ist ein Beispielprogramm:

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

Ausgang:

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