在前缀元素下没有xmlns的XmlDocument CreateElement

我正在尝试使用以下代码中的C#XmlDocument类来编写一个SOAP请求到ebay FindingAPI Web服务:

XmlDocument doc = new XmlDocument(); XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("soap", "Envelope", "http://www.w3.org/2003/05/soap-envelope")); root.SetAttribute("xmlns", "http://www.ebay.com/marketplace/search/v1/services"); XmlElement header = (XmlElement)root.AppendChild(doc.CreateElement("soap", "Header", "http://www.w3.org/2003/05/soap-envelope")); XmlElement body = (XmlElement)root.AppendChild(doc.CreateElement("soap", "Body", "http://www.w3.org/2003/05/soap-envelope")); XmlElement request = (XmlElement)body.AppendChild(doc.CreateElement("findItemsByKeywordsRequest")); XmlElement param = (XmlElement)request.AppendChild(doc.CreateElement("keywords")); param.InnerText = "harry potter phoenix"; 

并且,上面代码的XML输出是:

     harry potter phoenix    

但是,由于findItemsByKeywordsRequest元素中有额外的xmlns =“”属性,服务器无法识别此XML。 所需的XML输出应如下所示:

     harry potter phoenix    

有谁知道我的代码有什么问题,请给我一些提示。 谢谢!

因为您的文档具有在最外层元素中声明的默认命名空间,所以您必须在每个子元素上重复该命名空间,以避免添加额外的空元素。

更改requestparam元素声明以包含"http://www.ebay.com/marketplace/search/v1/services"命名空间

 XmlElement request = (XmlElement)body.AppendChild(doc.CreateElement("findItemsByKeywordsRequest", "http://www.ebay.com/marketplace/search/v1/services")); XmlElement param = (XmlElement)request.AppendChild(doc.CreateElement("keywords", "http://www.ebay.com/marketplace/search/v1/services")); 

通过这些更改,您的代码将生成以下XML:

     harry potter phoenix