OrElse OrElse - 5 months ago 29
Vb.net Question

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>
<cap>dd</cap>
</setup>
</configuration>

Answer

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