2017-05-15 47 views
0

下面的代碼將創建而不是如何強制它成爲<soap12:Body>標記。Xml使用Soap12標籤的自定義元素

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

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

     } 


    } 
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了工作演示。

+0

如果想要格式化如下? <?xml version =「1.0」encoding =「utf-8」?>; ; Andrea superhuman1314