【问题标题】:LINQ to XML query (basic)LINQ to XML 查询(基本)
【发布时间】:2009-12-08 20:05:45
【问题描述】:

我有一个如下格式的xml

   "<root>"
   "<page>"
   "<title>text</title>"
   "<text attrib1="1">some text</text>"
   "<text attrib1="2">some text</text>"
   "<text attrib1="3">some text</text>"
   "<text attrib1="4">some text</text>"

   "</page>"

   "<page>"
   "<title>text</title>"
   "<text attrib1="1">some text</text>"
   "<text attrib1="2">some text</text>"
   "<text attrib1="3">some text</text>"
   "<text attrib1="4">some text</text>"

   "</page>"
  "</root>"

忽略“”

现在我想要这样的结果 xml

      "<root>"
     "<title>text</title>"
     "<text attrib1="4">some text</text>"
     "<title>text</title>"
     "<text attrib1="4">some text</text>"
     "</root>"

这可以在一个查询中实现吗? 我使用两个查询尝试了以下操作

        var titleElms =
            from t in allElements
            select
                new
                {
                    Title = t.Element("title")
                };

        var textElms =
            from t in allText
            where (string)t.Attribute("attrib1").Value == "4"
            select
            t;

我对此不满意。那么还有其他方法吗?请帮忙。

【问题讨论】:

  • 你能用 XML 而不是文本来说明你想做什么吗?
  • 嘿,对不起,我无法在此处粘贴 XML,所有标签都被删除了.. :'(
  • 把它放在一个代码块中,就像你对 c# 所做的那样
  • 你还没有真正解释你想要做什么 - 例如,“pbname”从哪里来?
  • 现在应该没问题了....抱歉打嗝

标签: linq-to-xml


【解决方案1】:

我不认为这会给你你想要的,因为查询会产生一个 Ienumerable 对象。这意味着您想要一个具有大量标题和文本字段的单个对象。这将返回一个对象,其标题和文本是 Ienumerable 对象中的对象。

所以在您的示例中,您将拥有一个包含两个对象的对象,每个匿名对象现在都包含标题和文本。一旦你有了这个,你可以按照你想要的方式构建 xml。它与您的解决方案并没有太大的不同,但根据要求,它将为您提供一个 linq 查询。或者至少给你一个想法。

    XElement Results = XElement.Load("c:\\test.xml"); //load you xml
    XNamespace NameSpace = Results.Name.Namespace;
    var xe = (from page in Results.Elements(NameSpace + "page")
              let  title = page.Elements(NameSpace+"title")                      
              let text = page.Elements(NameSpace+"text").Where(a=>a.Attribute("attrib1").Value.Equals("4"))   
              where text.Count() > 0 
        //the where is simply to remove any unncessary data 
        //if there was ever a page that didn't have attrib1 = 4

            select new {title, text});

希望这至少能给你一些新的想法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多