C # XmlDocument Nodes

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); 
+3
source share
4 answers

There can only be one root root in an XML document. Otherwise, it is poorly formed. You will need to create 2 xml documents and combine them together if you need to send them at the same time.

+9
source

Throws an exception because you are trying to create invalid xml. XmlDocument will only generate generated xml.

You can do this using XMLWriter and set the XmlWriterSettings.ConformanceLevel for the fragment, or you can create two XmlDocuments and write them to a single stream.

+2
source

Create two separate XML documents and combine their string representation.

0
source

It looks like your node structure will always be the same. (I do not see conditional logic.) If the structure is constant, you can define an XML template string. Load this line into an XML document and make SelectNode to populate individual nodes.

It can be easier / cleaner than programmatically creating roots, elements, and nodes.

0
source

Source: https://habr.com/ru/post/1381345/


All Articles