2014-12-23 43 views
0

當我嘗試添加屬性時,我總是會遇到異常,爲什麼它不起作用?將屬性添加到XML節點總是失敗

前綴「」「不能從重新定義」到相同的開始元素標籤內「http://ws.plimus.com」 。

代碼

var docXml = new XElement("param-encryption", 
    new XAttribute("xmlns", "http://ws.plimus.com"), 
    new XElement("parameters")); 

var s = docXml.ToString(); 

我想導致像

<param-encryption xmlns="http://ws.plimus.com"> 
    <parameters> 


    </parameters> 
</param-encryption> 
+0

這是一個根元素? – Amit

+0

@Amit是的,這是根元素。 – Tomas

回答

0

這最簡單的方法就是讓LINQ到XML的元素名稱指定命名空間自動執行此操作:

XNamespace ns = "http://ws.plimus.com"; 
var docXml = new XElement(ns + "param-encryption", new XElement(ns + "parameters")); 

的結果:

<param-encryption xmlns="http://ws.plimus.com"> 
    <parameters /> 
</param-encryption> 
0

試試這個 -

XNamespace aw = "http://ws.plimus.com"; 
XElement root = new XElement("param-encryption", 
    new XAttribute(XNamespace.Xmlns + "aw", "http://ws.plimus.com"), 
    new XElement("Child", "child content") 
); 
Console.WriteLine(root); 

(編輯): - 使用這個,如果你不想命名空間別名

XNamespace aw = "http://ws.plimus.com"; 
    XElement root = new XElement(aw + "param-encryption", 
     new XAttribute("xmlns", "http://ws.plimus.com"), 
     new XElement(aw + "Child", "child content") 
    ); 
+0

這不會創建OP描述的XML。 – JLRishe