查找元素的XDocument? [英] Finding element in XDocument?
问题描述
我有一个简单的XML
I have a simple XML
<AllBands>
<Band>
<Beatles ID="1234" started="1962">greatest Band<![CDATA[lalala]]></Beatles>
<Last>1</Last>
<Salary>2</Salary>
</Band>
<Band>
<Doors ID="222" started="1968">regular Band<![CDATA[lalala]]></Doors>
<Last>1</Last>
<Salary>2</Salary>
</Band>
</AllBands>
然而,
However ,
当我想达到门乐队,并改变其ID:
when I want to reach the "Doors band" and to change its ID :
using (var stream = new StringReader(result))
{
XDocument xmlFile = XDocument.Load(stream);
var query = from c in xmlFile.Elements("Band")
select c;
...
查询
没有结果
但
如果我写的 xmlFile.Elements()。元素(带)
所以它并找到它。
If I write xmlFile.Elements().Elements("Band")
so it Does find it.
这是什么问题?
从需要根的完整路径?
如果是这样,为什么它不工作,指定 AllBands
?
And if so , Why did it work without specify AllBands
?
请问的XDocument
导航要求我知道满级结构向下到所需的元素?
Does the XDocument
Navigation require me to know the full level structure down to the required element ?
推荐答案
元素()
将只检查直接儿童 - 其中在第一种情况是根元素,在根元素的第二种情况下的儿童,因此,你在第二种情况下的匹配。如果你只是想任何匹配的后代使用后裔()
而不是:
Elements()
will only check direct children - which in the first case is the root element, in the second case children of the root element, hence you get a match in the second case. If you just want any matching descendant use Descendants()
instead:
var query = from c in xmlFile.Descendants("Band") select c;
此外,我建议你重新构造你的XML:乐队的名字应该是一个属性或元素值,而不是元素的名称本身 - 这使得查询(为此事和架构验证)更难,即是这样的:
Also I would suggest you re-structure your Xml: The band name should be an attribute or element value, not the element name itself - this makes querying (and schema validation for that matter) much harder, i.e. something like this:
<Band>
<BandProperties Name ="Doors" ID="222" started="1968" />
<Description>regular Band<![CDATA[lalala]]></Description>
<Last>1</Last>
<Salary>2</Salary>
</Band>
这篇关于查找元素的XDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!