2011-08-10 75 views
0

我需要能夠操縱一個XML像這樣一個模式:操作XML的XDocument XmlDocument的C#

<?xml version='1.0' encoding='UTF-8' standalone='no'?> 
<SOAP-ENVELOPE:Envelope xmlns:SOAP-ENVELOPE='http://schemas.xmlsoap.org/soap/envelope/'> 
<SOAP-ENVELOPE:Header> 
    <Authorization> 
     <FromURI/> 
     <User/> 
     <Password/> 
     <TimeStamp/> 
    </Authorization> 
    <Notification> 
     <NotificationURL/> 
     <NotificationExpiration/> 
     <NotificationID/> 
     <MustNotify/> 
    </Notification> 
</SOAP-ENVELOPE:Header> 
<SOAP-ENVELOPE:Body SOAP-ENVELOPE:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'> 
</SOAP-ENVELOPE:Body> 

我需要添加數據FromURI,用戶,密碼,NotificiationURL,MustNotify等,並在身體內我門坎需要動態地添加:

<SOAPSDK4:APIOperation xmlns:SOAPSDK4="http://www.someserver.com/message/"> 
</SOAPSDK4:APIOperation> 

要最終構建所需要的Web服務,但可以使用XD輕鬆完成APIOperation內構造用於創建一棵樹。

我一直在尋找關於如何操縱信封內的數據一週的信息的麻煩,在這裏我需要這樣做與樹不同的水平。

+0

正如你所說,使用XDocument的構造非常簡單。你有什麼問題? –

+0

我有麻煩添加數據到標題部分到每個元素。 然後,我需要能夠在APIOperation部分創建任意數量的具有它的結構的項目,我不完全確定如何使用XDocument來完成此操作,這就是爲什麼我現在正在使用XmlDocument一塊一塊地創建。 – Elder

+0

「我有麻煩」一點也不清楚。如果你能提供更多細節,我們可能會幫助你更多。 –

回答

1

爲了給你一個想法:

var doc = XDocument.Load(...); 
XNamespace envNs = "http://schemas.xmlsoap.org/soap/envelope/"; 
var fromUri = doc.Root 
     .Element(envNs + "Header") 
     .Element("Authorization") 
     .Element("FromURI"); 
fromUri.Value = "http://trst"; 
doc.Save(...); 
0

如果我正確理解您的問題,則可以使用StringBuilder創建SOAP信封,然後將該字符串轉換爲XDocument

1

最後,我決定使用XmlDocument的從頭創建:

XmlDocument Request = new XmlDocument(); 
XmlDeclaration declarationRequest = Request.CreateXmlDeclaration("1.0", "UTF-8", "no"); 
Request.InsertBefore(declaracionRequest, Request.DocumentElement); 
XmlElement soapEnvelope = Request.CreateElement("SOAP-ENVELOPE", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/"); 
Request.AppendChild(soapEnvelope); 
XmlElement soapHeader = Request.CreateElement("SOAP-ENVELOPE", "Header", Request.DocumentElement.NamespaceURI); 
Request.DocumentElement.AppendChild(soapHeader); 
XmlElement soapBody = Request.CreateElement("SOAP-ENVELOPE", "Body", Request.DocumentElement.NamespaceURI); 
soapBody.SetAttribute("SOAP-ENVELOPE:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/"); 
Request.DocumentElement.AppendChild(soapBody); 
XmlElement nodeAutorization = Request.CreateElement("Authorization"); 
XmlElement nodeFromURI = Request.CreateElement("FromURI"); 
... 
soapHeader.AppendChild(nodoAutorization); 
nodeAutorization.AppendChild(nodoFromURI); 
nodeAutorization.AppendChild(nodoUser); 
... 

並以同樣的方式一切。問題是,使用所有元素和難以在同一級別生成許多節點的代碼變得非常大。

我不知道是否有更好的做法或更容易,但這個工作。