Saving the result of a linq query to an XML file
Here is the original xml file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<setup>
<cap>33</cap>
</setup>
<setup>
<cap>dd</cap>
</setup>
</configuration>
In the example below I delete the node where cap equals to 33
Dim Cap As integer = 33
Dim query = From q In XElement.Load(Environment.CurrentDirectory & "\sample.xml").Elements("setup") _
Where q.Value = Cap _
Select q
For Each q In query
If Cap = q.Element("cap").Value Then q.Remove()
Next
Now how can I write back the result of the query to the .xml file? Like...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<setup>
&l开发者_StackOverflowt;cap>dd</cap>
</setup>
</configuration>
Well, you can just create a new XDocument with the data. (C# syntax, but easily converted...)
XDocument doc = new XDocument(new XElement("configuration", query));
doc.Save(file);
How about using XPath:
Imports System.Xml.XPath
Module Module1
Sub Main()
Dim doc = XDocument.Load("foo.xml")
doc.XPathSelectElements("//setup/cap[text() = 'dd']/..").Remove()
Console.WriteLine(doc)
End Sub
End Module
精彩评论