递归遍历 xml 树并将元素值推送到自定义类中
其中一个“units”元素可以是许多“unit”元素,这些“unit”元素又具有一个“units”元素。
我想将每个单元的unitName写入自定义类,并使用prop UnitName将前一个/父单元的unitName写入prop ParentUnitName。
我也不确定递归方法应该返回什么类型的数据......最好是带有平面列表的列表。
你会怎么做?
<units>
<unit>
<unitName>Test05</unitName>
<units>
<unit>
<unitName>Test03</unitName>
<units>
<unit>
<unitName>Test04</unitName>
<units>
<unit>
<unitName>Test07</unitName>
<units>
<unit>
<unitName>Test01</unitName>
</unit>
</units>
</unit>
</units>
</unit>
</units>
</unit>
</units>
</unit>
</units>
Whitin a "units" element can be many "unit" elements which again have a "units" element.
I want to write the unitName of each unit into a custom class with prop UnitName AND the unitName of the previous/parent unit into the prop ParentUnitName.
I am also unsure what type of data the recursive method should return... best would be a List with a flat list.
How would you do that?
<units>
<unit>
<unitName>Test05</unitName>
<units>
<unit>
<unitName>Test03</unitName>
<units>
<unit>
<unitName>Test04</unitName>
<units>
<unit>
<unitName>Test07</unitName>
<units>
<unit>
<unitName>Test01</unitName>
</unit>
</units>
</unit>
</units>
</unit>
</units>
</unit>
</units>
</unit>
</units>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更喜欢以这种方式编写一个类:
然后使用 XmlSerializer 对其进行序列化/反序列化。
I would prefer writing a class in this way:
and then serialize / deserialize it with XmlSerializer.
查看 XDocument 类。
它有多种方法可以帮助轻松解析 Xml。在您的情况下,它看起来像这样:
这将迭代 xml 文档中的所有
unitName
元素,您可以对它们执行任何您想要的操作。编辑:将 xdoc.Descendants 更改为 xdoc.Elements,因此它现在递归工作并产生预期结果。
Have a look at the XDocument class.
It has a variety of methods available to help with parsing Xml easily. In your case it would look something like:
This will iterate through all
unitName
elements in the xml document and you can do whatever you want with them.Edit: Changed xdoc.Descendants to xdoc.Elements, so it works recursively now and yields the expected results.