提问人:cmcperillano03 提问时间:2/28/2023 最后编辑:Peter Csalacmcperillano03 更新时间:2/28/2023 访问量:203
使用 XMLDocument 获取 XML 的特定父节点内的所有特定节点
Get all specific nodes inside a specific parent node of an XML using XMLDocument
问:
我有以下 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"];
}
答:
0赞
Peter Csala
2/28/2023
#1
您只需要两个 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>
- 注意:的结果是一个,所以你必须在foreach中显式使用才能使用
SelectNodes
XmlNodeList
XmlElement
OuterXml
- 注意:的结果是一个,所以你必须在foreach中显式使用才能使用
输出将是
<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" />
0赞
pfx
2/28/2023
#2
下面的 XPATH 语句将允许您在单个调用中获取这些条件。
请注意 in 允许在 1 个以上的级别进行匹配,从该级别开始排除您不需要的级别。//
filter//condition
//fetch/entity/link-entity/filter
//fetch/entity/link-entity/filter//condition
var conditions = doc.SelectNodes("//fetch/entity/link-entity/filter//condition");
foreach (var condition in conditions)
{
Console.WriteLine(condition.OuterXml);
}
评论
filter
filter
link-entity
linkEntityElem.SelectNodes("filter")