LINQ: Remove Element from XML based on attribute value?

假如想象 提交于 2019-12-19 02:46:06

问题


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();

回答1:


You can use the following code snippet:

xdoc.XPathSelectElement("Projects/Project[@projectName = 'project1']").Remove();



回答2:


Remove is a (void) method call, not a function that can return a value. You probably want something like this:

var elementsToRemove = from elemet in xdoc.Elements("Projects").Elements("Project")
                       where elemet.Attribute("projectName").Value == "project1"
                       select elemet;

foreach (var e in elementsToRemove)
    e.Remove();

LINQ is a query language, it's (mainly) used to return something. Performing actions on these elements is usually a separate step.




回答3:


You could use

xdoc.Elements("Projects").Elements("Project").Where(
                    elemet => elemet.Attribute("projectName").Value == "project1")
.ToList().ForEach(i => i.Remove());

or

(from elemet in xdoc.Elements("Projects").Elements("Project")
                          where elemet.Attribute("projectName").Value == "project1"
                          select elemet).ToList().ForEach(i => i.Remove());



回答4:


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



来源:https://stackoverflow.com/questions/5004481/linq-remove-element-from-xml-based-on-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!