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

Pet*_*ras 15 .net c# xml soap

全部,我想创建一个肥皂信封xml文件,例如.

<soap:Envelope soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding" xmlns:soap="http://www.w3.org/2001/12/soap-envelope"></soap:Envelope>
Run Code Online (Sandbox Code Playgroud)

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

这给了我

<soap:Envelope encodingStyle="http://www.w3.org/2001/12/soap-encoding" xmlns:soap="http://www.w3.org/2001/12/soap-envelope"></soap:Envelope>
Run Code Online (Sandbox Code Playgroud)

您用来XAttribute为元素添加前缀,我可以XAttribute用来添加前缀XAttribute吗?

谢谢,P

Bra*_*ger 11

在创建'encodingStyle'XAttribute时(通过使用ns + "encodingStyle")指定命名空间:

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

两个参数XAttribute构造函数需要一个XName作为第一个参数.这可以从一个隐式构造string(如在您的问题的代码),或通过"加入"直接在stringXNamespace来创建XName(如上).

  • 谢谢。仅仅是我还是这是一个设计不良的API?某些“聪明的”运算符重载但没有构造函数重载会做同样的事情吗?什么? (2认同)