如何从 xml 读取嵌套对象?
我有一个看起来像这样的 xml 文件,
<questions>
<question>
<text>What color is an orange?</text>
<answer>blue</answer>
<answer>yellow</answer>
<answer>orange</answer>
</question>
<question>
<text>What color is a banana?</text> ...
我已经设法弄清楚如何使用对象的公共方法将属性和值读取到属性中,但是我如何获得包含“答案”的“问题”对象对象,序列化比使用 linq-to-xml 更好
这是使用 linq:
var data = from query in questionData.Descendants("question")
select new Quiz.Question
{
QuestionTitle = (string)query.Attribute("title"),
QuestionText = query.Element("text") != null ? query.Element("text").Value.Trim() : string.Empty,
QuestionImage = query.Element("image") != null ? query.Element("image").Attribute("src").Value : string.Empty
...
在 linq 中,我如何将另一个节点序列化为另一个对象,假设我在“中有一个“答案”对象列表问题”?
I have an xml file that looks something like this
<questions>
<question>
<text>What color is an orange?</text>
<answer>blue</answer>
<answer>yellow</answer>
<answer>orange</answer>
</question>
<question>
<text>What color is a banana?</text> ...
I've managed to figure out how to read attributes and values into the properties using the public methods for the object, but how would i get a "Question" object that would contain "Answer" objects, would it be better to just serialize than use linq-to-xml
This is using linq:
var data = from query in questionData.Descendants("question")
select new Quiz.Question
{
QuestionTitle = (string)query.Attribute("title"),
QuestionText = query.Element("text") != null ? query.Element("text").Value.Trim() : string.Empty,
QuestionImage = query.Element("image") != null ? query.Element("image").Attribute("src").Value : string.Empty
...
in linq how do I go about serializing another node as another object, say i have a list of "answer" object in "question"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为此使用序列化,但如果您想有一种完全可定制的方式来执行此操作,我会推荐这样做:
在问题类中:
并且当您想阅读时:
从 FromXmlElement 内部,您可以调用另一个复杂类型的相同方法,如果你的类有一个复杂类型的属性等等。
You can use serialization for this, but if you want to have a totally custimizable way of doing this I would recommend this:
In Question class:
and when you want to read:
from inside the FromXmlElement you can call same method of another complex type if your class has a property of a complex type and so on.