0

I have a XMl like this :

  <?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>

I want to search for word and if node exists get name and link
So i try for search with this code

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
                     };

and this is SelectWord class

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

and the result always is null !
I think my query is wrong, what is need for change ?

Sara
  • 209
  • 1
  • 3
  • 10

1 Answers1

1

Please try this:

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
    };
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
  • Thanks but noe have a new problem ! Here at **Elements** : `.Select(x => x.Elements("Word")).Where (What is here for Attribute?) (x => x.Attribute is not exists )` – Sara Aug 15 '15 at 20:27
  • Thank you, is it possible to get all result nods and not only first ? – Sara Aug 15 '15 at 21:27
  • @Sara All Word subnodes in node Cid? – Alexander Petrov Aug 15 '15 at 21:33
  • we have some categorys and in each category have many words and can be duplicate name but with different id and link – Sara Aug 15 '15 at 21:49