当前位置: 首页 > 编程语言 > C#

C#XmlDocument节点分享

时间:2023-04-10 23:46:19 C#

C#XmlDocument节点XmlDocument我在创建它时遇到了问题。当我尝试添加第二个时:或者它会抛出一个错误:System.InvalidOperationException:Thisdocumentalreadyhasa'DocumentElement'node。我猜这是因为标准XmlDocument只有1个根节点。有什么办法吗?到目标之前,我的代码是:XmlDocumentxmlDoc=newXmlDocument();XmlDeclarationxmlDeclaration=xmlDoc.CreateXmlDeclaration("1.0","utf-8",null);XmlElementrootNode=xmlDoc.CreateElement("AccessRequest");rootNode.SetAttribute("xml:lang","en-US");xmlDoc.InsertBefore(xmlDeclaration,xmlDoc.DocumentElement);xmlDoc.AppendChild(rootNode);XmlElementlicenseNode=xmlDoc.CreateElement("AccessLicenseNumber");XmlElementuserIDNode=xmlDoc.CreateElement("UserId");XmlElementpasswordNode=xmlDoc.CreateElement("密码");XmlTextlicenseText=xmlDoc.CreateTextNode("mylicense");XmlTextuserIDText=xmlDoc.CreateTextNode("myusername");XmlTextpasswordText=xmlDoc.CreateTextNode("mypassword");rootNode.AppendChild(licenseNode);rootNode.AppendChild(userIDNode);rootNode.AppendChild(密码节点);licenseNode.AppendChild(licenseText);userIDNode.AppendChild(userIDText);passwordNode.AppendChild(passwordText);XmlElementrootNode2=xmlDoc.Create元素(“跟踪请求”);xmlDoc.AppendChild(rootNode2);一个XML文档只能有一个根节点,否则它的格式不正确。如果你需要一次发送两个文档,你需要创建2个xml文档并将它们连接在一起。它抛出异常,因为您正在尝试创建无效的xml。XmlDocument只会生成格式正确的xml。您可以使用XMLWriter并将XmlWriterSettings.ConformanceLevel设置为Fragment,也可以创建两个XmlDocuments并将它们写入同一个流。构建两个单独的XML文档并连接它们的字符串表示形式。看起来你的节点结构总是一样的。(我没有看到任何条件逻辑。)如果结构是常量,您可以定义XML模板字符串。将该字符串加载到XML文档中并执行SelectNode以填充单个节点。这可能比以编程方式创建根、元素和节点更简单/更清晰。以上就是C#学习教程:C#XmlDocument节点分享的全部内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: