【问题标题】:Writing LINQ to XML query for filtering a xml string编写 LINQ to XML 查询以过滤 xml 字符串
【发布时间】:2012-01-10 06:31:19
【问题描述】:

我有以下 xml 字符串:

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

如何编写一个 Linq to xml 查询,该查询按 name = "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;

如何将过滤列表转换回 xml 字符串?

【问题讨论】:

    标签: linq c#-4.0 linq-to-xml


    【解决方案1】:

    您可以从现有查询中投影一个新的 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();
    

    【讨论】:

      【解决方案2】:

      您是否尝试过使用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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-23
        • 1970-01-01
        • 2021-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多