2010-08-04 9 views
12

Potrzebuję utworzyć atrybut "abc" z przedrostkiem "xx" dla elementu "aaa". Poniższy kod dodaje przedrostek, ale dodaje również przestrzeń nazwUri do elementu.Jak dodać atrybuty do xml przy użyciu XmlDocument w C# .net CF 3.5

Wymagane wyjściowe:

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

mój kod:

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

Powyższy kod generuje:

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

Pożądany wynik jest

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

I deklaracja „xx” atrybutu powinny być wykonywane w węźle głównym jak:

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

Jak można dostać, jeśli wyjście w deisred formacie? Jeśli plik XML nie ma pożądanego formatu, nie można go już przetworzyć.

Czy ktoś może pomóc?

Dzięki Vicky

Odpowiedz

32

wierzę, że to tylko kwestia ustawienia odpowiedniego atrybutu bezpośrednio na węźle głównym. Oto przykładowy program:

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

wyjściowa:

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