【问题标题】:query for select value in xelement查询 xelement 中的选择值
【发布时间】:2015-08-15 19:34:16
【问题描述】:

我有一个这样的 XML:

  <?xml version="1.0" encoding="utf-8"?>
  <Words>
     <List>
        <Cid Name="c1" ID="11">
          <Word Name="test1" ID="1">
            <Name>test1</Name>
            <Link>yahoo.com</Link>
          </Word>
        </Cid>
        <Cid Name="c2" ID="22">
          <Word Name="w0" ID="0">
            <Name>test0</Name>
            <Link>yahoo0.com</Link>
          </Word>
          <Word Name="w1" ID="1">
            <Name>test</Name>
            <Link>yahoo.com</Link>
          </Word>
          <Word Name="w1" ID="2">
            <Name>mehrdad</Name>
            <Link>google.com</Link>
          </Word>
        </Cid>
      </List>
  </Words>

我想搜索单词,如果节点存在获取名称和链接
所以我尝试使用此代码进行搜索

XDocument doc = XDocument.Load(data);

            var relatedDocs =
                from CatID in
                doc.Elements("Cid")
                     .Where(x => (string)x.Attribute("ID").Value == ctId.ToString())
                     .Select(x => x.Elements("Word"))
                     .Where  (What is here ? don have access to Attribute so what ?)  (x => x.Attribute("Name").Value == sName)

                     select new SelectWord {
                         NameAtt = CatID.Attribute("Name").Value,
                         IDAtt = CatID.Attribute("ID").Value,
                         Name = CatID.Element("Name").Value,
                         Link = CatID.Element("URL").Value
                     };

这是 SelectWord 类

class SelectWord
        {
            public string NameAtt { get; set; }
            public string IDAtt { get; set; }
            public string Name { get; set; }
            public string Link { get; set; }
        }

结果总是 null !
我认为我的查询是错误的,需要改变什么?

【问题讨论】:

    标签: xml linq xelement


    【解决方案1】:

    请试试这个:

    var relatedDocs =
        from CatID in doc.Root.Element("List").Elements("Cid")
            .Where(x => x.Attribute("ID").Value == ctId.ToString())
            .SelectMany(x => x.Elements("Word")
                .Where(w => w.Attribute("Name").Value == sName))
        select new SelectWord
        {
            NameAtt = CatID.Attribute("Name").Value,
            IDAtt = CatID.Attribute("ID").Value,
            Name = CatID.Element("Name").Value,
            Link = CatID.Element("Link").Value
        };
    

    【讨论】:

    • 谢谢,但没有新问题!在 Elements 处:.Select(x =&gt; x.Elements("Word")).Where (What is here for Attribute?) (x =&gt; x.Attribute is not exists )
    • 谢谢,是否有可能获得所有结果点头,而不仅仅是第一个?
    • @Sara 节点 Cid 中的所有 Word 子节点?
    • 我们有一些类别,每个类别中有很多单词,可以是重复的名称,但具有不同的 id 和链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多