2010-11-16 27 views
0

这里是原始的XML文件保存LINQ查询的结果为XML文件

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <setup> 
     <cap>33</cap> 
    </setup> 
    <setup> 
     <cap>dd</cap> 
    </setup> 
</configuration> 

在下面的例子中我删除节点,在帽等于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 

现在怎么能我将查询的结果写回到.xml文件中?像...

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <setup> 
     <cap>dd</cap> 
    </setup> 
</configuration> 

回答

1

那么,你可以用数据创建一个新的XDocument。 (C#语法,但很容易地转换...)

XDocument doc = new XDocument(new XElement("configuration", query)); 
doc.Save(file); 
+0

太近...我试图像昏暗文档作为的XDocument doc.Add(<%= query %>) doc.Save(...但它没有解决!谢谢。 – OrElse 2010-11-16 09:14:35

0

如何使用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