如何使用XLINQ获得最内在的孩子

时间:2009-12-21 20:53:06

标签: linq-to-xml

我有这个xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" manifestId="{b91dc6f6-a837-4c5a-bdc8-77a93107af77}" mandatory="No" xmlns="urn:schemas-microsoft-com:PAG:updater-application-block:v2:manifest">
<files base="http:abc/def" hashComparison="Yes" hashProvider="SHA1Managed">
<file source="123.dll" hash="oZlt8qISQxTNETMTSAfhdzJisj+kgir7oWS64+VMbRRCOXXE" />
<file source="234.dll" hash="39UEf/AIp+pSfH4WbftTPVysryCDJBJd/URmUbANpTiAmGHm" />
<file source="abc.dll" hash="2X5d8WfRtBuzLKNZ8geVfy3AmOKaUD7cSI17PbRyF8ds66Cx"  />
</files>
</manifest>

我想从这个XML中获取所有文件节点,以便我可以获得源,哈希和瞬态的值以供我进一步工作。

请在XLINQ告诉我......

2 个答案:

答案 0 :(得分:1)

如果您不关心父节点,可以使用Descendants选择器来简化代码:

XNamespace ns = "urn:schemas-microsoft-com:PAG:updater-application-block:v2:manifest";
var files = XDocument.Parse(xml).Descendants(ns + "file").Select(x => new {
   Source = (string)x.Attribute("source"),
   Hash =  (string)x.Attribute("hash")
});

文件现在将存储IEnumerable的强类型(匿名)对象,这些对象公开了属性'Source'和'Hash'

答案 1 :(得分:0)

使用Elements选择器:

XDocument d = XDocument.Parse(xml);
XNamespace ns = "urn:schemas-microsoft-com:PAG:updater-application-block:v2:manifest";
var files = d.Elements(ns + "manifest").Elements(ns + "files").Elements(ns + "file");

请注意,由于清单标记中没有前缀xmlns声明,因此需要XNamespace。

相关问题