2010-12-10 69 views
12

全部, 我想創建一個soap信封xml文件,例如。如何在.NET中爲XAttribute設置名稱空間前綴?

<soap:Envelope soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding" xmlns:soap="http://www.w3.org/2001/12/soap-envelope"></soap:Envelope> 

我使用System.Xml.Linq要做到這一點,但我無法弄清楚如何將soap添加前綴encodingStyle屬性。

到目前爲止,我有這樣的:

XNamespace ns = XNamespace.Get("http://www.w3.org/2001/12/soap-envelope"); 
XAttribute prefix = new XAttribute(XNamespace.Xmlns + "soap", ns); 
XAttribute encoding = new XAttribute("encodingStyle", "http://www.w3.org/2001/12/soap-encoding"); 

XElement envelope = new XElement(ns + "Envelope", prefix, encoding); 

這給了我

<soap:Envelope encodingStyle="http://www.w3.org/2001/12/soap-encoding" xmlns:soap="http://www.w3.org/2001/12/soap-envelope"></soap:Envelope> 

您使用XAttribute添加前綴的元素,我可以使用XAttribute添加前綴到XAttribute ??!

感謝,P

回答

9

,當你(通過使用ns + "encodingStyle")創造 '的encodingStyle' XAttribute指定命名空間:

XAttribute encoding = new XAttribute(ns + "encodingStyle", "http://www.w3.org/2001/12/soap-encoding"); 

two-parameter XAttribute constructor需要一個XName作爲第一個參數。這可以從string(如在您的問題中的代碼中)隱含地構建,或直接通過將string「添加」到XNamespace以創建XName(如上)來直接構建。

+1

謝謝。它只是我還是這是一個設計非常糟糕的API?一些「聰明的」運算符重載,但沒有構造函數重載做同樣的事情?什麼? – 2010-12-10 07:08:34

+0

請注意,XAttribute構造函數需要一個`XName`。 `string`有一個隱式轉換爲`XName`,但你也可以通過將一個`XNamespace`添加到字符串名稱來創建一個。 System.Xml.Linq廣泛使用運算符重載和隱式/顯式轉換運算符;例如,`(int)elem.Attribute(「count」)`將讀取`count`屬性的字符串值(在`elem`上),將其解析爲一個整數並返回該值。這不是很容易發現,但結果非常簡潔/簡潔/難以理解(適當刪除)代碼。 – 2010-12-10 08:03:22

1

您需要將XAttribute的XName與XNamespace結合使用。我知道吧...無論如何嘗試這個。

XNamespace soap = "http://www.w3.org/2001/12/soap-envelope"; 
XAttribute encoding = new XAttribute(soap + "encodingStyle", 
    "http://www.w3.org/2001/12/soap-encoding"); 
相關問題