Попытка проанализировать дерево XML с Linq к XML (C#)

Попробуйте это и, пожалуйста, дайте мне знать, если есть какие-либо проблемы

 public getCountofProducts() {
    this.productService.getAllProducts().subscribe
    (
      (products) => {
          if (products!= null) {
             this.getCount(products);
             return this.productsLength;
           }
           else{
             return 0;
           }
       }
     );
 }

 public getCount(products){
    this.productsLength=this.products.length;
 }
6
задан Kamil Zadora 26 April 2009 в 22:49
поделиться

3 ответа

Ваш код не работает, потому что вы возвращаете все элементы ответа, потому что вы не ограничивали их, основываясь на вопросе, из которого они пришли. Вы можете добавить это ограничение или вместо подзапроса, основанного на документе, вы можете создать подзапрос на основе самого элемента вопроса.

List<Question> questions = (from question in xdoc.Element("survey").Element("questions").Elements("question")
         select new Question
         {
           text = question.Element("text").Value,
           anwsers = (from answer in question.Element("answers").Elements("answer")
                select new Anwser
                {
                  content = answer.Element("v").Value
                }).ToList()
         }).ToList();
7
ответ дан 9 December 2019 в 20:48
поделиться

Похоже, проблема в том, что вы начинаете с xdoc. в вашем внутреннем выборе, если вы хотите изменить его на:

from answer in xml.Elements("answers").Elements("answer")

С вами все будет в порядке. Это должно работать, потому что XML содержит элемент вопроса.

1
ответ дан 9 December 2019 в 20:48
поделиться

You were very close. In the select new parts you don't need () after the class names. Also you want to use .Descendents() instead of .Elements(). The only other part was the answers should be using the xml var not going back to the original document, this gives you the answers associated with the question.

List<Question> questions = (from xml in xdoc.Descendants("question")
                                    select new Question
                                    {
                                        text = xml.Element("text").Value,
                                        answers =
                                            (from anwsers in xml.Descendants("answer")
                                             select new Answer
                                             {
                                                 Content = anwsers.Element("v").Value
                                             }

                                            ).ToList()
                                    }).ToList();
4
ответ дан 9 December 2019 в 20:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: