简体   繁体   中英

Cant add data to xml from list using linq

This code doesn't work for me and I can't understand why.

xmlDoc.Element("results").Add(
                new XElement("user",
                    new XAttribute("id", user.Id),
                    new XAttribute("facebookid", user.FacebookId),
                    new XAttribute("email", user.Email),
                    new XAttribute("totalpoints", totalpoints)
                    ).Add(
                            user.Answers.Select(value => new XElement("question",
                            new XAttribute("id", value.QuestionId),
                            new XAttribute("answer_id", value.AnswerId),
                            new XAttribute("points", value.Points)))
                          )
                  );

I'm trying to create this

<results>
  <user id="2323" facebookId="3254954795743957" email="david@gmail" totalPoints="">
    <question id="1" answer_id="3" points="0" />
    <question id="2" answer_id="1" points="1" />
  </user>
</results>
xmlDoc.Element("results").Add(
    new XElement("user",
        new XAttribute("id", user.Id),
        new XAttribute("facebookid", user.FacebookId),
        new XAttribute("email", user.Email),
        new XAttribute("totalpoints", totalpoints),
        user.Answers.Select(value => new XElement(
                "question",
                new XAttribute("id", value.QuestionId),
                new XAttribute("answer_id", value.AnswerId),
                new XAttribute("points", value.Points)
            ))
        )
    );

The problem was that the Add method returns void so you can't continue with another Add over the void result. Also, for attributes you need to use XAttribute , not XElement .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM