LINQ:根据属性值从 XML 中删除元素?
如何根据匹配的属性值删除 xml 中的任何元素?
这是我的 XML:
<Projects>
<Project serverUrl="tcp://xyz1:xxx/sdfsdf.rem" projectName="project1" />
<Project serverUrl="tcp://xyz2:xxx/sdfsdf.rem" projectName="project2" />
<Project serverUrl="tcp://xyz3:xxx/sdfsdf.rem" projectName="project3" />
<Project serverUrl="tcp://xyz4:xxx/sdfsdf.rem" projectName="project4" />
<Project serverUrl="tcp://xyz5:xxx/sdfsdf.rem" projectName="project5" />
<Project serverUrl="tcp://xyz6:xxx/sdfsdf.rem" projectName="project6" />
</Projects>
我正在使用以下 LINQ 查询:
var remove = from elemet in xdoc.Elements("Projects").Elements("Project")
where elemet.Attribute("projectName").Value == "project1"
select elemet.Parent.Remove();
我在 select as 上遇到编译时错误:
select中表达式的类型 条款不正确
编辑答案: 这个对我有用。谢谢大家
var xElement = (from elemet in xdoc.Elements("Projects").Elements("Project")
where elemet.Attribute("projectName").Value == foundProject
select elemet);
xElement.Remove();
How can I remove any element in xml based on matched attribute value?
Here is my XML :
<Projects>
<Project serverUrl="tcp://xyz1:xxx/sdfsdf.rem" projectName="project1" />
<Project serverUrl="tcp://xyz2:xxx/sdfsdf.rem" projectName="project2" />
<Project serverUrl="tcp://xyz3:xxx/sdfsdf.rem" projectName="project3" />
<Project serverUrl="tcp://xyz4:xxx/sdfsdf.rem" projectName="project4" />
<Project serverUrl="tcp://xyz5:xxx/sdfsdf.rem" projectName="project5" />
<Project serverUrl="tcp://xyz6:xxx/sdfsdf.rem" projectName="project6" />
</Projects>
I am using the following LINQ query:
var remove = from elemet in xdoc.Elements("Projects").Elements("Project")
where elemet.Attribute("projectName").Value == "project1"
select elemet.Parent.Remove();
I am getting compile time error on select as :
The type of expression in select
clause is Incorrect
EDIT ANSWER:
this one works for me. Thanks All
var xElement = (from elemet in xdoc.Elements("Projects").Elements("Project")
where elemet.Attribute("projectName").Value == foundProject
select elemet);
xElement.Remove();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Remove
是一个 (void) 方法调用,而不是一个可以返回值的函数。您可能想要这样的东西:LINQ 是一种查询语言,它(主要)用于返回某些内容。对这些元素执行操作通常是一个单独的步骤。
Remove
is a (void) method call, not a function that can return a value. You probably want something like this:LINQ is a query language, it's (mainly) used to return something. Performing actions on these elements is usually a separate step.
你可以使用
或
You could use
or
您可以使用以下代码片段:
You can use the following code snippet:
Remove()
是您在 XNode 上调用的方法。您的查询试图选择没有任何意义的方法。您真正想要做的是选择要删除的项目,然后对所选项目调用Remove() 方法。您可以在这里找到一个示例:
XNode.Remove方法
Remove()
is a method you call on an XNode. Your query is trying to select the method which doesn't make any sense.What you actually want to do is select the item you wish to remove, then call the Remove() method on the selected item. You can find an example here:
XNode.Remove Method