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

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

 

我使用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); 

这给了我

  

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

谢谢,P

在创建’encodingStyle’XAttribute时使用ns + "encodingStyle"指定命名空间:

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

双参数XAttribute构造函数将XName作为第一个参数。 这可以从string隐式构造(如在问题中的代码中),也可以直接通过“添加” stringXNamespace来创建XName (如上所述)。

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