如何使用XmlDocument类创建无文档根节点的XML文档?
使用XmlDocument创建无顶级根节点的XML片段解决方案
我明白你想要生成一段没有统一根节点的XML内容,这种场景下直接用XmlDocument确实容易踩坑——因为标准XML要求必须有且仅有一个顶级根元素,但XmlDocument的设计本身是遵循这个标准的,不过我们可以通过一些技巧实现你要的输出效果。
方法一:用XmlDocument实现
你之前的代码可能没正确处理XML声明和节点的添加逻辑,下面是完整的可运行代码:
using System; using System.IO; using System.Xml; class Program { static void Main() { XmlDocument xmlDoc = new XmlDocument(); // 首先添加XML声明节点 XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmlDeclaration); // 创建并添加Initials节点 XmlElement initialsNode = xmlDoc.CreateElement("Initials"); initialsNode.InnerText = "ANP"; xmlDoc.AppendChild(initialsNode); // 创建并添加MedicalPracticeName节点 XmlElement practiceNameNode = xmlDoc.CreateElement("MedicalPracticeName"); practiceNameNode.InnerText = "Dr. Anny"; xmlDoc.AppendChild(practiceNameNode); // 创建并添加Start节点 XmlElement startNode = xmlDoc.CreateElement("Start"); startNode.InnerText = "2016-11-17"; xmlDoc.AppendChild(startNode); // 创建Logon节点及其子节点 XmlElement logonNode = xmlDoc.CreateElement("Logon"); XmlElement userIdNode = xmlDoc.CreateElement("UserId"); userIdNode.InnerText = "admin"; logonNode.AppendChild(userIdNode); XmlElement passwordNode = xmlDoc.CreateElement("Password"); passwordNode.InnerText = "abcde"; logonNode.AppendChild(passwordNode); xmlDoc.AppendChild(logonNode); // 将XML内容输出为字符串 using (StringWriter sw = new StringWriter()) using (XmlTextWriter xw = new XmlTextWriter(sw)) { xmlDoc.WriteTo(xw); string xmlContent = sw.ToString(); Console.WriteLine(xmlContent); } } }
方法二:用XmlWriter更灵活实现
如果只是要输出你要的XML片段,XmlWriter是更合适的选择——它不需要遵循XmlDocument的单根节点约束,代码更简洁:
using System; using System.IO; using System.Xml; class Program { static void Main() { using (StringWriter sw = new StringWriter()) { XmlWriterSettings settings = new XmlWriterSettings { Indent = true, // 可选:格式化输出 OmitXmlDeclaration = false // 保留XML声明 }; using (XmlWriter writer = XmlWriter.Create(sw, settings)) { writer.WriteStartDocument(); // 逐个写入顶级元素 writer.WriteElementString("Initials", "ANP"); writer.WriteElementString("MedicalPracticeName", "Dr. Anny"); writer.WriteElementString("Start", "2016-11-17"); // 写入嵌套的Logon节点 writer.WriteStartElement("Logon"); writer.WriteElementString("UserId", "admin"); writer.WriteElementString("Password", "abcde"); writer.WriteEndElement(); writer.WriteEndDocument(); } string xmlContent = sw.ToString(); Console.WriteLine(xmlContent); } } }
注意事项
- 严格来说,没有单根节点的XML是不符合W3C标准的,很多XML解析器可能会报错。如果是和外部系统交互,最好确认对方能接受这种格式。
- 如果后续需要修改XML内容,
XmlDocument方式更方便;如果只是一次性生成输出,XmlWriter效率更高。
内容的提问来源于stack exchange,提问作者Lets Do Green
相关产品推荐
相关产品推荐

