如何通过名称获取节点?
这是一项简单的任务,但我无法完成它。给定以下 XML:
<?xml version="1.0" encoding="UTF-8"?>
<product>
<item1></item1>
<item2></item2>
<item3></item3>
</product>
我想获取 product
中的所有节点。以下两次尝试没有返回任何节点,我不明白为什么:
XDocument meteoDoc = XDocument.Load("data.xml");
foreach (var item in meteoDoc.Descendants("product")) {//...}
foreach (var item in meteoDoc.Descendants().Where(x => x.Name == "product").Nodes()) {//...}
按照预期,以下内容将返回所有节点:
foreach (var item in meteoDoc.DescendantNodes()) { //...}
感谢任何提示,我看不到问题...:-/
It's a simple task, but I can't make it work. Given the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<product>
<item1></item1>
<item2></item2>
<item3></item3>
</product>
I'd like to get all nodes within product
. Following two attempts return no nodes, I don't see why:
XDocument meteoDoc = XDocument.Load("data.xml");
foreach (var item in meteoDoc.Descendants("product")) {//...}
foreach (var item in meteoDoc.Descendants().Where(x => x.Name == "product").Nodes()) {//...}
The following, as expected, would return me all nodes:
foreach (var item in meteoDoc.DescendantNodes()) { //...}
Thx for any tipps, I can't see the problem... :-/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的第一次尝试是请求所有
后代
称为产品
。您的第二次尝试是查找名为product
的所有后代的直接子节点。它可能正在寻找根元素内的后代...如果您知道根元素称为
product
,您可以只使用:(我无法测试恐怕你现有的代码到底为什么不适合你。)
请注意,
后代
只会找到后代元素 - 如果您想要所有后代节点,你需要后代节点
< /a> 方法。Your first attempt is asking for all the
Descendants
calledproduct
. Your second attempt is finding the direct child nodes of all descendants calledproduct
.It's possible that it's looking for descendants within the root element... if you know that the root element is called
product
, you could just use:(I can't test your existing code to find out exactly why it's not working for you right now, I'm afraid.)
Note that
Descendants
will only find descendant elements - if you want all descendant nodes, you need theDescendantNodes
method.使用这个:
Use this:
试试这个:
Try this:
我对 xml 做了一些更改,这样数据的格式更加良好,我可以给您一段完成您的任务的代码。
I have made a few change to xml, in this way the data is more well-formed and i can give you a piece of code that accomplish your task.