如何在.NET中为XAttribute设置名称空间前缀?

问题描述:

全部, 我想创建一个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

,当你(通过使用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

您需要将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");