I need to be able to manipulate a XML with a schema like this:
<?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>
I need to add the data for FromUR开发者_Go百科I, User, Password, NotificiationURL, MustNotify, etc and within the body I sill need to add dynamically:
<SOAPSDK4:APIOperation xmlns:SOAPSDK4="http://www.someserver.com/message/">
</SOAPSDK4:APIOperation>
To finally construct the structure within APIOperation that is needed for the web service but can be easily done using XDocument to create a tree.
I've been having troubles to find information for a week on how to manipulate data within the envelope and here I need to do so with tree different levels.
To give you an idea:
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(...);
Finally I decided to create it from scratch using 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);
...
And in the same way everything else. The problem is, the code gets pretty large using all the elements and kind of difficult to generate many nodes at the same level.
I do not know if there are better practices or something easier but this worked.
If I am understanding your question correctly, you could just use a StringBuilder
to create the SOAP envelope, and then convert that string to a XDocument
.
精彩评论