I have one XML file
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<File>
<Cars>
<Car>
<Color>Blue</Color>
<Year>1988</Year>
</Car>
<Car>
<Color>Green</Color>
<Year>1989</Year>
</Car>
<Car>
<Color>Yellow</Color>
<Year>1989</Year>
</Car>
</Cars>
</File>
I want to create a filter on this file with this object :
public class condition
{
public string color { get; set; }
public string year { get; set; }
}
List<condition> c = new List<condition>
{
new condition()
{
color = "Green",
year = "1989"
},
new condition()
{
color = "Blue",
year = "1988"
}
};
I want to take only car with (color = Green and year = 1989) OR (color = blue and year = 1988)
But I don't have idea how to do this. Maybe with XDocument and Linq.Dynamic ?
You can easily filter xml in linq using a XDocument
. This function will remove all nodes based on a filter using the Remove()
extension method.
private void RemoveCars(string color, string year)
{
var doc = XDocument.Load("<myxml>...</myxml>");
doc.Element("File")
.Element("Cars")
.Elements("Cars")
.Where(c=> c.Element("color").Value == color
&& c.Element("Year").Value == year)
.Remove();
doc.Save("c:\\mypath\\my.xml");
}
Another Option you can use Linq to xml
//XElement xFile = XElement.Load("D:/Sample.xml");
XElement xFile = XElement.Parse
(@"<File>
<Cars>
<Car>
<Color>Blue</Color>
<Year>1988</Year>
</Car>
<Car>
<Color>Green</Color>
<Year>1989</Year>
</Car>
<Car>
<Color>Yellow</Color>
<Year>1989</Year>
</Car>
</Cars>
</File> ");
List<condition> c = new List<condition>
{
new condition()
{
color = "Green",
year = "1989"
},
new condition()
{
color = "Blue",
year = "1988"
}
};
var s = new XElement("Cars",
from cc in c
select new XElement("Car",
new XElement("Color", cc.color),
new XElement("Year", cc.year)
)
);
var result = xFile.Descendants("Cars").Intersect(s.Descendants("Cars"));
var fileXML = new XElement("File", result);
fileXML.Save("D:/Result.xml");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.