我在XDocument中有以下XML片段
<axes dimension="y">
<axis id="y11" scale="log" label="label1">
...
</axis>
<axis id="y12" scale="log" label="label1">
...
</axis>
</axes>
<axes dimension="x">
<axis id="x0" label="">
...
</axis>
<axis id="x1" label="">
...
</axis>
</axes>
这是在XDocument中,我想从中移除y12轴,剩下剩下的。所以,最终的输出将是
<axes dimension="y">
<axis id="y11" scale="log" label="label1">
...
</axis>
</axes>
<axes dimension="x">
<axis id="x0" label="">
...
</axis>
<axis id="x1" label="">
...
</axis>
</axes>
如何做到这一点?
我试过这个,但它不起作用
xDocument
.Elements("axes")
.Where(x => (string)x.Attribute("dimension") == "y")
.Elements("axis")
.Where(x => (string)x.Attribute("id") == "y12")
.Remove();
答案 0 :(得分:0)
由于您正在使用XDocument而不是XElement,因此您应该使用Root
属性以使Elements
方法按预期工作并从根目录中找到元素:
而不是xDocument.Elements("axes")...
使用:
xDocument.Root.Elements("axes")
.Where(x => (string)x.Attribute("dimension") == "y")
.Elements("axis")
.Where(x => (string)x.Attribute("id") == "y12")
.Remove();
或者,您可以直接使用Root
跳过Descendants
:
xDocument.Descendants("axes")
.Where(x => (string)x.Attribute("dimension") == "y")
.Elements("axis")
.Where(x => (string)x.Attribute("id") == "y12")
.Remove();
答案 1 :(得分:0)
试试这个:
xDocument.Descendants("axis")
.Where(x => (string)x.Attribute("id") == "y12")
.Remove();