使用c添加、编辑和删除XML多级节点
本文关键字:删除 XML 多级 节点 编辑 添加 使用 | 更新日期: 2023-09-27 17:59:18
这是我的XML结构,我需要一个C#程序来添加、编辑和删除N级别的元素。
<root>
<TopLevelMenu ID="&File">
<MenuItem ID="New" OnClick="_New" />
<MenuItem ID="Open" OnClick="_Open" />
<MenuItem ID="-" />
<MenuItem ID="Close" OnClick="_Close" />
<MenuItem ID="-" />
<MenuItem ID="E&xit" OnClick="_Exit" />
</TopLevelMenu>
<TopLevelMenu ID="&Edit">
<MenuItem ID="Undo" OnClick="_Undo" />
<MenuItem ID="-" />
<MenuItem ID="Cut" OnClick="_Cut" />
<MenuItem ID="Copy" OnClick="_Copy" />
<MenuItem ID="Paste" OnClick="_Paste" />
<MenuItem ID="-" />
<MenuItem ID="Options">
<MenuItem ID="Sub Menu Item">
<MenuItem ID="Sub Sub Menu Item" />
</MenuItem>
</MenuItem>
</TopLevelMenu>
</root>
试试这个递归代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication34
{
class Program
{
static void Main(string[] args)
{
string input =
"<root>'n" +
"<TopLevelMenu ID='"Imports&FileImports'">'n" +
"<MenuItem ID='"ImportsNewImports'" OnClick='"Imports_NewImports'"/>'n" +
"<MenuItem ID='"ImportsOpenImports'" OnClick='"Imports_OpenImports'"/>'n" +
"<MenuItem ID='"Imports-Imports'" />'n" +
"<MenuItem ID='"ImportsCloseImports'" OnClick='"Imports_CloseImports'"/>'n" +
"<MenuItem ID='"Imports-Imports'"/>'n" +
"<MenuItem ID='"ImportsE&xitImports'" OnClick='"Imports_ExitImports'"/>'n" +
"</TopLevelMenu'n>" +
"<TopLevelMenu ID='"Imports&EditImports'">'n" +
"<MenuItem ID='"ImportsUndoImports'" OnClick='"Imports_UndoImports'"/>'n" +
"<MenuItem ID='"Imports-Imports'"/>'n" +
"<MenuItem ID='"ImportsCutImports'" OnClick='"Imports_CutImports'"/>'n" +
"<MenuItem ID='"ImportsCopyImports'" OnClick='"Imports_CopyImports'"/>'n" +
"<MenuItem ID='"ImportsPasteImports'" OnClick='"Imports_PasteImports'"/>'n" +
"<MenuItem ID='"Imports-Imports'"/>'n" +
"<MenuItem ID='"ImportsOptionsImports'">'n" +
"<MenuItem ID='"ImportsSub Menu ItemImports'">'n" +
"<MenuItem ID='"ImportsSub Sub Menu ItemImports'"/>'n" +
"</MenuItem>'n" +
"</MenuItem>'n" +
"</TopLevelMenu>'n" +
"</root>'n";
XDocument doc = XDocument.Parse(input);
var results = doc.Descendants("TopLevelMenu").Elements("MenuItem").Select(y => GetMenu(y)).ToList();
}
static object GetMenu(XElement element)
{
if (!element.HasElements)
{
return element.Attribute("ID").Value;
}
else
{
return (new { id = element.Attribute("ID").Value, child = GetMenu(element.Element("MenuItem"))});
}
}
}
}