使用C#生成带SOAP-ENV前缀的SOAP XML文档问题求助
如何在C#中生成带SOAP-ENV前缀的SOAP XML文档
你遇到的问题很常见——用XmlDocument创建带命名空间前缀的XML元素时,直接把前缀写在元素名里是不够的,因为XmlDocument需要明确把前缀和对应的命名空间URI绑定起来,否则会自动忽略前缀。
问题根源
你当前用doc.CreateElement("SOAP-ENV:Envelope")创建元素时,XML解析器并没有将"SOAP-ENV"前缀和你定义的http://schemas.xmlsoap.org/soap/envelope/命名空间关联起来,所以最终输出时会自动去掉前缀,只保留命名空间属性。
解决方法
要创建带命名空间前缀的元素,需要使用XmlDocument.CreateElement的重载方法,明确指定前缀、本地名称和命名空间URI。这样XmlDocument就能正确识别前缀与命名空间的对应关系,输出时保留前缀。
以下是修正后的完整代码:
XmlDocument doc = new XmlDocument(); // 创建带前缀和命名空间的Envelope元素 XmlNode envelopeNode = doc.CreateElement( "SOAP-ENV", // 指定前缀 "Envelope", // 元素本地名称 "http://schemas.xmlsoap.org/soap/envelope/" // 对应的命名空间URI ); doc.AppendChild(envelopeNode); // 创建带前缀和命名空间的Body元素 XmlNode bodyNode = doc.CreateElement( "SOAP-ENV", "Body", "http://schemas.xmlsoap.org/soap/envelope/" ); envelopeNode.AppendChild(bodyNode); // 创建地址相关元素(设置xmlns为空) XmlNode addressLine1 = doc.CreateElement("AddressLine1"); addressLine1.SetAttribute("xmlns", ""); addressLine1.InnerText = "50 W TOWN ST"; bodyNode.AppendChild(addressLine1); XmlNode addressLine2 = doc.CreateElement("AddressLine2"); addressLine2.SetAttribute("xmlns", ""); addressLine2.InnerText = "STE 400"; bodyNode.AppendChild(addressLine2); XmlNode city = doc.CreateElement("City"); city.SetAttribute("xmlns", ""); city.InnerText = "COLUMBUS"; bodyNode.AppendChild(city); XmlNode state = doc.CreateElement("State"); state.SetAttribute("xmlns", ""); state.InnerText = "OH"; bodyNode.AppendChild(state); XmlNode zip = doc.CreateElement("Zip"); zip.SetAttribute("xmlns", ""); zip.InnerText = "43215"; bodyNode.AppendChild(zip); XmlNode zip4 = doc.CreateElement("Zip4"); zip4.SetAttribute("xmlns", ""); zip4.InnerText = ""; bodyNode.AppendChild(zip4); // 输出最终XML Console.WriteLine(doc.OuterXml);
代码说明
- CreateElement重载使用:通过
CreateElement(prefix, localName, namespaceURI)方法,让XmlDocument明确前缀与命名空间的绑定关系,确保输出时保留SOAP-ENV前缀。 - 地址元素的xmlns属性:目标XML中地址元素的
xmlns=""表示默认命名空间为空,直接给这些元素添加xmlns属性并设为空字符串即可实现。
运行这段代码后,就能生成你需要的带SOAP-ENV前缀的SOAP XML文档了。
内容的提问来源于stack exchange,提问作者Venkat Krishna
相关产品推荐
相关产品推荐

