I am trying to get UPS tracking information and, according to their example, I need to build the request as follows:
<?xml version="1.0" ?> <AccessRequest xml:lang='en-US'> <AccessLicenseNumber>YOURACCESSLICENSENUMBER</AccessLicenseNumber> <UserId>YOURUSERID</UserId> <Password>YOURPASSWORD</Password> </AccessRequest> <?xml version="1.0" ?> <TrackRequest> <Request> <TransactionReference> <CustomerContext>guidlikesubstance</CustomerContext> </TransactionReference> <RequestAction>Track</RequestAction> </Request> <TrackingNumber>1Z9999999999999999</TrackingNumber> </TrackRequest>
I am having trouble creating this using 1 XmlDocument in C #. When I try to add the second: <?xml version="1.0" ?> or the <TrackRequest> it throws an error:
System.InvalidOperationException: this document already has a 'DocumentElement' node.
I assume this is due to the fact that the standard XmlDocument will only have 1 root node. Any ideas?
Here is my code:
XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); XmlElement rootNode = xmlDoc.CreateElement("AccessRequest"); rootNode.SetAttribute("xml:lang", "en-US"); xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); xmlDoc.AppendChild(rootNode); XmlElement licenseNode = xmlDoc.CreateElement("AccessLicenseNumber"); XmlElement userIDNode = xmlDoc.CreateElement("UserId"); XmlElement passwordNode = xmlDoc.CreateElement("Password"); XmlText licenseText = xmlDoc.CreateTextNode("mylicense"); XmlText userIDText = xmlDoc.CreateTextNode("myusername"); XmlText passwordText = xmlDoc.CreateTextNode("mypassword"); rootNode.AppendChild(licenseNode); rootNode.AppendChild(userIDNode); rootNode.AppendChild(passwordNode); licenseNode.AppendChild(licenseText); userIDNode.AppendChild(userIDText); passwordNode.AppendChild(passwordText); XmlElement rootNode2 = xmlDoc.CreateElement("TrackRequest"); xmlDoc.AppendChild(rootNode2);
source share