C# XML 节点适用于元素但不适用于元素 [英] C# XML Node Works with Element But Not with Elelments
问题描述
我想在下面的xml数据中获取suras的子节点;
i want to get the child nodes of suras in the following xml data;
<suras alias="chapters">
<sura index="1" ayas="7" start="0" name="الفاتحة" tname="Al-Faatiha" ename="The Opening" type="Meccan" order="5" rukus="1" />
<sura index="2" ayas="286" start="7" name="البقرة" tname="Al-Baqara" ename="The Cow" type="Medinan" order="87" rukus="40" />
<sura index="3" ayas="200" start="293" name="آل عمران" tname="Aal-i-Imraan" ename="The Family of Imraan" type="Medinan" order="89" rukus="20" />
<sura index="4" ayas="176" start="493" name="النساء" tname="An-Nisaa" ename="The Women" type="Medinan" order="92" rukus="24" />
<sura index="5" ayas="120" start="669" name="المائدة" tname="Al-Maaida" ename="The Table" type="Medinan" order="112" rukus="16" />
</suras>
suras 节点运行正常,但是当我尝试访问 sura
节点时,我无法将其作为 suras
的 Elements
>;
如您所见,如果我调试父节点,即 suras 节点,我可以清楚地正确看到第一个和最后一个节点.但是当我尝试查询它的 Elements 或 Decendents 时,我什么也没得到.检查以下屏幕截图;同样,如果我将代码更改为 Element("sura")
而不是 Elements("sura")
,那么它只显示第一个节点检查这个;所以,我的问题是,为什么我没有得到子节点,即 surah?
The suras node is comming fine but when i try to access the sura
node, i can't get it as an Elements
of suras
;
as you can see if i debug the parent i.e suras node, i can clearly see the first and last node correctly. But when i try to query its Elements or Decendents, i dont' get anything. Check the following screen shot;
Similarly, if i change my code to Element("sura")
instead of Elements("sura")
, then it only shows first node check this;
So, my question is, Why i am not getting the child nodes i.e surah?
推荐答案
它确实有效,只是你不能那样看.尝试遍历 Elements("suras")
,你会得到很好的结果:
It is actually worked, you just can't see it that way. Try to iterate through Elements("suras")
and you'll get the result just fine :
....
var test2 = test.Elements("sura");
foreach (XElement sura in test2)
{
MessageBox.Show(sura.ToString())
//or print to VS output window :
//Debug.WriteLine(sura.ToString());
}
或者通过调用 .ToList()
或 .ToArray()
来具体化查询,以便无需循环即可查看实际结果:
Or materialize the query to be able to see the actual result without looping, by calling .ToList()
or .ToArray()
:
var test2 = test.Elements("sura").ToList();
这篇关于C# XML 节点适用于元素但不适用于元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!