我有以下xml字符串:
<report>
<item id="4219" Co="6063" LastName="Doe" FirstName="John"/>
<item id="2571" Co="6063" LastName="Doe" FirstName="Jane"/>
</report>
如何将Linq写入xml查询,按名称=“Jane”过滤并将其写回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 :(得分: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);
答案 1 :(得分: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();