我有将类似于下面的结构的XML文件:如何根据多个父母的属性删除子元素?
<?xml version="1.0" encoding="utf-8"?>
<Root Attr1="Foo" Name="MyName" Attr2="Bar" >
<Parent1 Name="IS">
<Child1 Name="Kronos1">
<GrandChild1 Name="Word_1"/>
<GrandChild2 Name="Word_2"/>
<GrandChild3 Name="Word_3"/>
<GrandChild4 Name="Word_4"/>
</Child1>
<Child2 Name="Kronos2">
<GrandChild1 Name="Word_1"/>
<GrandChild2 Name="Word_2"/>
<GrandChild3 Name="Word_3"/>
<GrandChild4 Name="Word_4"/>
</Child2>
</Parent1>
</Root>
中的元素不会在定义他们可以具有比其它文件不同的值。我所知道的是每个元素的“名称”属性,它总是被定义的。我需要能够根据该名称操作和/或删除选定元素内的数据。例如:removeElement("MyName.IS.Kronos1.Word_1")
将删除Child1
父级下的GrandChild1
元素。
我的问题是,虽然使用LINQ to XML查询,我无法正确选择该元素。使用此:
private IEnumerable<XElement> findElements(IEnumerable<XElement> docElements, string[] names)
{
// the string[] is an array from the desired element to be removed.
// i.e. My.Name.IS ==> array[ "My, "Name", "IS"]
IEnumerable<XElement> currentSelection = docElements.Descendants();
foreach (string name in names)
{
currentSelection =
from el in currentSelection
where el.Attribute("Name").Value == name
select el;
}
return currentSelection;
}
要查找我需要删除的元素产生这样的结果:
<?xml version="1.0" encoding="utf-8"?>
<Root Attr1="Foo" Name="MyName" Attr2="Bar" >
<Parent1 Name="IS">
<Child1 Name="Kronos1">
<GrandChild2 Name="Word_2"/>
<GrandChild3 Name="Word_3"/>
<GrandChild4 Name="Word_4"/>
</Child1>
<Child2 Name="Kronos2">
<GrandChild2 Name="Word_2"/>
<GrandChild3 Name="Word_3"/>
<GrandChild4 Name="Word_4"/>
</Child2>
</Parent1>
</Root>
调试看来,我做的是重新搜索同一文档后,但每次都有不同的名字。如何根据多个父属性名称搜索和选择特定元素?
需要注意的是,XML的大小(即元素的等级)也是可变的。这意味着可以有2层(家长)或6层(伟大 - 大孩子)。但是,我需要能够查看根节点的Name
属性。
这实际上工作得很好。甚至给我的老板留下了深刻的印象:) – KronoS
你实际上可以使用'.FirstOrDefault()',如果你不想处理这个异常,它将返回null。 – KronoS
编辑到功能的例子,那么你确实不需要例外。 @KronoS –