我如何包装根的所有子元素? 我目前拥有的例子:
<?xml version="1.0" encoding="utf-16"?>
<root>
<element>YUP</element>
<element>YUP</element>
<element>YUP</element>
</root>
但是我需要它添加一个新的子代,它封装了root的所有子代,如下所示:
<?xml version="1.0" encoding="utf-16"?>
<root>
<newsubroot>
<element>YUP</element>
<element>YUP</element>
<element>YUP</element>
</newsubroot>
</root>
我没有首选(或强制)技术 - 欢迎同时使用XmlDocument
或XDocument
的任何示例。
答案 0 :(得分:1)
XDocument xDoc = XDocument.Parse(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<root>
<element>YUP</element>
<element>YUP</element>
<element>YUP</element>
</root>");
var newsubroot = new XElement("newsubroot");
newsubroot.Add(xDoc.Root.Elements());
xDoc.Root.RemoveAll();
xDoc.Root.Add(newsubroot);
答案 1 :(得分:1)
使用LINQ2XML的一种可能解决方案如下所示:
代码如下所示:
var xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<root>
<element>YUP</element>
<element>YUP</element>
<element>YUP</element>
</root>";
try
{
var document = XDocument.Parse(xml);
var root = document.Root;
// get all "element" elements
var yups = root.Descendants("element");
// get a copy of the nodes that are to be moved inside new node
var copy = yups.ToList();
// remove the nodes from the root
yups.Remove();
// put them in the new sub node
root.Add(new XElement("newSubRoot", copy));
// output or save
Console.WriteLine(document.ToString()); // document.Save("c:\\xml.xml");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
输出结果为:
<root>
<newSubRoot>
<element>YUP</element>
<element>YUP</element>
<element>YUP</element>
</newSubRoot>
</root>
答案 2 :(得分:0)
您可以使用如下的XDocument
XDocument doc = XDocument.Parse(xml);
foreach (XElement subroot in doc.Descendants("newsubroot"))
{
// get subroot elements
foreach (var subsubroot in subroot.Descendants("element"))
{
// get subsubroot elements
}
}