2012-01-09 52 views
1

我有以下XML字符串:寫作的LINQ to XML查詢過濾一個XML字符串

<report> 
    <item id="4219" Co="6063" LastName="Doe" FirstName="John"/> 
    <item id="2571" Co="6063" LastName="Doe" FirstName="Jane"/> 
</report> 

我怎樣寫一個LINQ到通過名稱=「簡」過濾器和寫回一個XML查詢XML字符串

我有下面的代碼至今:

XDocument reportXmlDoc = XDocument.Parse(_report); //This is the string var assigned with data above 
var filteredList = from x in fullReportXmlDoc.Descendants("item") 
      where x.Attribute("FirstName").Value == "Jane" 
      select x; 

如何轉換filteredList回一個XML字符串?

回答

0

您可以從現有的查詢項目中的新XML樹:

var filteredList = 
    from x in fullReportXmlDoc.Descendants("item") 
    where x.Attribute("FirstName").Value == "Jane" 
    select new XElement("report", x).ToString(); 

或許,在一個更一般的情況:

string result = new XElement("report", 
    from x in fullReportXmlDoc.Descendants("item") 
    where x.Attribute("FirstName").Value == "Jane" 
    select x).ToString(); 
0

您是否試過使用SaveOptions.DisableFormatting來獲取XElement的XML字符串?它看起來像這樣爲你的情況:

XDocument reportXmlDoc = XDocument.Parse(_report); //This is the string var assigned with data above 
var elementStrings = from x in fullReportXmlDoc.Descendants("item") 
    where x.Attribute("FirstName").Value == "Jane" 
    select x.ToString(SaveOptions.DisableFormatting);