如何将额外的根添加到加载的 xml 文件 c# [英] How to add extra root to loaded xml file c#
问题描述
谁能告诉我如何在 C# 中向加载的 xml 文件中添加额外的根目录?
Can someone tell me how to add extra root to loaded xml file in c#?
现在我有:
<object>
<obj_name>hero1</obj_name>
<field>
</field>
</object>
<object>
<obj_name>hero2</obj_name>
<field>
</field>
</object>
在我想要之后:
<objects>
<object>
<obj_name>hero1</obj_name>
<field>
</field>
</object>
<object>
<obj_name>hero2</obj_name>
<field>
</field>
</object>
</objects>
我的代码:
//Create XmlDocument instance
XmlDocument doc = new XmlDocument();
//Before loading xml file whtie spaces are allowed
doc.PreserveWhitespace = false;
//Loading xml file
doc.Load(@"..\..\input.xml");
//Deleting white spaces
doc.PreserveWhitespace = true;
推荐答案
您目前拥有的不是 XML,因为 XML 中不允许有两个根元素.
What you have currently is not XML because two root elements are not allowed in XML.
您的标题和开头问题与您的代码不一致.您已经有两个根元素,并且您正在尝试将它们包装在一个根元素中,以便您拥有格式良好的 XML.
Your title and opening question are inconsistent with your code. You already have two root elements, and you're trying to wrap them in a single root element so that you do have well-formed XML.
您不能使用 XML 库处理格式不正确的 XML(因为它不是 XML);首先你必须修复它.将文件作为文本读取,添加包装器根元素,然后将其解析为 XML.有关处理XML"问题的更多详细信息,请参阅如何解析无效(错误/格式不正确)的 XML?
You cannot process non-well-formed XML with XML libraries (because it isn't XML); first you have to repair it. Read the file as text, add the wrapper root element, and then parse it as XML. For more details on dealing with problem "XML," see How to parse invalid (bad / not well-formed) XML?
这篇关于如何将额外的根添加到加载的 xml 文件 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!