C#XmlDocument节点

我正在尝试访问UPS跟踪信息,根据他们的示例,我需要构建一个这样的请求:

  YOURACCESSLICENSENUMBER YOURUSERID YOURPASSWORD      guidlikesubstance  Track  1Z9999999999999999  

我在使用C#中的1个XmlDocument创建此问题时遇到问题。 当我尝试添加第二个: or the 它会抛出一个错误:

System.InvalidOperationException:此文档已有“DocumentElement”节点。

我猜这是因为标准的XmlDocument只有1个根节点。 有任何想法吗?

到目前为止,我的代码是:

 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); 

XML文档只能有一个根节点。 否则它的形成不好。 如果需要一次发送两个文档,则需要创建2个xml文档并将它们连接在一起。

它抛出exception是因为你试图创建无效的xml。 XmlDocument只会生成格式良好的xml。

您可以使用XMLWriter并将XmlWriterSettings.ConformanceLevel设置为Fragment,也可以创建两个XmlDocuments并将它们写入同一个流中。

构建两个单独的XML文档并连接它们的字符串表示。

看起来您的节点结构始终相同。 (我没有看到任何条件逻辑。)如果结构是常量,您可以定义XML模板字符串。 将该字符串加载到XML文档中并执行SelectNode以填充单个节点。

这可能比以编程方式创建根,元素和节点更简单/更清晰。