我有以下 XML:
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">
<entity name="contact">
<attribute name="contactid" />
<link-entity name="ccl1007_studentjourney" from="ccl1007_contactid" to="contactid">
<filter type="and">
<condition attribute="statecode" operator="eq" value="0" />
<filter type="or">
<condition attribute="ccl1007_sjapplicantdayattendedon" operator="last-x-months" value="12" />
<condition attribute="ccl1007_sjapplicantdayattendedon" operator="next-x-years" value="5" />
</filter>
</filter>
</link-entity>
<filter>
<condition attribute="contactid" operator="eq" value="234" />
</filter>
</entity>
</fetch>
我想要做的是获取
<condition/>
节点内的所有<link-entity/>
节点并忽略<condition/>
.的其他实例
使用我的示例,我希望输出仅返回以下节点
<condition attribute="statecode" operator="eq" value="0" />
<condition attribute="ccl1007_sjapplicantdayattendedon" operator="last-x-months" value="12" />
<condition attribute="ccl1007_sjapplicantdayattendedon" operator="next-x-years" value="5" />
我尝试了以下但它只能循环包含第一个
<filter/>
标签的第一个
<condition/>
标签
XmlNode linkEntityElem = doc.GetElementsByTagName("link-entity")[0];
foreach (XmlNode child in linkEntityElem.SelectNodes("filter"))
{
var g = child.Attributes["attribute"];
}
你只需要两个 xpath 查询:
var linkEntity = doc.SelectSingleNode("//fetch/entity/link-entity");
var conditions = linkEntity.SelectNodes(".//condition");
foreach (XmlElement condition in conditions)
{
Console.WriteLine(condition.OuterXml);
}
SelectSingleNode
的参数会找到<lint-entity>
节点SelectNodes
的参数会查找<condition>
节点下的所有<link-entity>
节点,不管深度如何
SelectNodes
的结果是一个XmlNodeList
所以你必须在foreach中明确使用XmlElement
才能使用OuterXml
输出将是
<condition attribute="statecode" operator="eq" value="0" />
<condition attribute="ccl1007_sjapplicantdayattendedon" operator="last-x-months" value="12" />
<condition attribute="ccl1007_sjapplicantdayattendedon" operator="next-x-years" value="5" />
下面的 XPATH 语句将允许您在一次调用中获得这些条件。
注意
//
中的 filter//condition
以允许匹配超过 1 级。
//fetch/entity/link-entity/filter//condition
var conditions = doc.SelectNodes("//fetch/entity/link-entity/filter//condition");
foreach (XmlElement condition in conditions!)
{
Console.WriteLine(condition.OuterXml);
}