2010-08-04 20 views
12

"aaa" öğesi için "xx" önekiyle "abc" özniteliği oluşturmanız gerekir. Aşağıdaki kod öneki ekler, ancak aynı zamanda namespaceUri öğeye ekler.XmlDocument kullanarak C# .net CF 3.5 kullanarak öznitelikler nasıl eklenir?

Gerekli Çıktı:

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

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

Yukarıdaki kod oluşturur:

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

İstenilen çıkış

<mybody> 
<aaa xx:abc="ddd"/> 
<mybody/> 
olduğunu

Ve "xx" özelliğinin beyanı gibi kök düğüm yapılmalıdır:

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

Nasıl eğer deisred biçiminde çıkış almak? Xml bu istenen formatta değilse, o zaman işlenemez ..

Herkes yardımcı olabilir mi?

sayesinde Vicky

cevap

32

Ben sadece kök düğüm üzerinde doğrudan ilgili niteliğinin kurulması meselesi inanıyoruz. Aşağıda örnek bir 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); 
    } 
} 

Çıktı:

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