以下代码将创建,而不是如何强制它成为<soap12:Body>
标记。
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
xmlDoc.AppendChild(docNode);
XmlNode envelopeNode = xmlDoc.CreateElement("soap12", "Envelope", "http://www.w3.org/2003/05/soap-envelope");
xmlDoc.DocumentElement?.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlDoc.DocumentElement?.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
XmlNode bodyNode = xmlDoc.CreateNode(XmlNodeType.Element, "soap12", "Body", null);
envelopeNode.AppendChild(bodyNode);
xmlDoc.AppendChild(envelopeNode);
将导致
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<Body />
</soap12:Envelope>
而不是
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
</soap12:Body>
</soap12:Envelope>
答案 0 :(得分:0)
我更喜欢使用xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication55
{
class Program
{
static void Main(string[] args)
{
string header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" +
"</soap12:Envelope>";
XDocument doc = XDocument.Parse(header);
XElement envelope = doc.Root;
XNamespace nsSoap12 = envelope.GetNamespaceOfPrefix("soap12");
XElement body = new XElement(nsSoap12 + "Body");
envelope.Add(body);
}
}
答案 1 :(得分:0)
您需要将正确的命名空间传递给CreateNode
:
XmlNode bodyNode = xmlDoc.CreateNode(XmlNodeType.Element,
"soap12", "Body", "http://www.w3.org/2003/05/soap-envelope");
虽然使用更现代的LINQ to XML,但整个问题更简单:
XNamespace ns = "http://www.w3.org/2003/05/soap-envelope";
var doc = new XDocument(
new XElement(ns + "Envelope",
new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema"),
new XAttribute(XNamespace.Xmlns + "soap12", ns),
new XElement(ns + "Body")
)
);
有关正常工作的演示,请参阅this fiddle。