2010-08-04 29 views
12

我需要爲元素「aaa」創建一個前綴爲「xx」的屬性「abc」。以下代碼添加了前綴,但它也會將namespaceUri添加到元素。如何在c#中使用XmlDocument將屬性添加到xml中.net CF 3.5

所需的輸出:

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

我的代碼:

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

上面的代碼生成:

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

希望的輸出是

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

而「XX」屬性的聲明應該像根節點來完成:

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

怎樣才能獲得,如果在deisred格式輸出?如果xml不是這種所需的格式,那麼它不能被處理了..

任何人都可以幫忙嗎?

感謝, 玉萍

回答

32

我相信這只是直接在根節點上設置相關屬性的問題。下面是一個示例程序:

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

輸出:

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