无法获取包含特定文本的特定类型的子节点
本文关键字:类型 子节点 文本 包含特 获取 | 更新日期: 2023-09-27 18:25:36
使用下面的代码,我可以接收Xml中的所有<job>
元素。但是,当我尝试搜索具有名为<Name>
的子级并且其文本等于"receiverjob"
的作业时,即使该作业存在,SelectNodes()
方法也会返回零。
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNamespaceManager nsManager = new XmlNamespaceManager(dom.NameTable);
nsManager.AddNamespace("d", "http://quartznet.sourceforge.net/JobSchedulingData");
XmlNodeList jobElements = dom.DocumentElement.SelectNodes("descendant::d:job[name=receiverjob]", nsManager);
Xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file contains job definitions in schema version 2.0 format -->
<job-scheduling-data version="2.0" xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<processing-directives>
<overwrite-existing-data>true</overwrite-existing-data>
</processing-directives>
<schedule>
<job>
<name>receiverjob</name>
<group>receivergroup</group>
<job-type>Quartz.Server.ArgumentReceiverJob, Quartz.Server</job-type>
<job-data-map>
<entry>
<key>receivedargument</key>
<value>hamburger</value>
</entry>
</job-data-map>
</job>
<trigger>
<simple>
<name>argumentreceiverJobTrigger</name>
<group>argumentreceiverGroup</group>
<description>Simple trigger to simply fire sample job</description>
<job-name>receiverjob</job-name>
<job-group>receivergroup</job-group>
<misfire-instruction>SmartPolicy</misfire-instruction>
<repeat-count>-1</repeat-count>
<repeat-interval>10000</repeat-interval>
</simple>
</trigger>
<job>
<name>batchjob</name>
<group>batchGroup</group>
<job-type>Quartz.Server.BatchJob, Quartz.Server</job-type>
<durable>true</durable>
<recover>false</recover>
</job>
<trigger>
<cron>
<name>Trigger2</name>
<group>DEFAULT</group>
<job-name>batchjob</job-name>
<job-group>batchGroup</job-group>
<cron-expression>0/15 * * * * ?</cron-expression>
</cron>
</trigger>
<job>
<name>jobnamexxx</name>
</job>
<job>
<name>jobnamexxx</name>
</job>
<job>
<name>jobnamexxx</name>
</job>
</schedule>
</job-scheduling-data>
我不是XPath专家,但我怀疑您的查询现在正试图查找name
元素等于receiverjob
元素的作业。我怀疑你想要这样的东西:
"descendant::d:job[name/text()='receiverjob']"
也可能需要将name
元素限定在正确的命名空间中:
"descendant::d:job[d:name/text()='receiverjob']"
我强烈地考虑使用LINQ to XML,然而,在真正简单的地方(IMO):
XDocument doc = XDocument.Load(textBoxFilePath.Text);
XNamespace ns = "http://quartznet.sourceforge.net/JobSchedulingData";
var jobs = doc.Descendants(ns + "job")
.Where(x => (string) x.Element(ns + "name") == "receiverjob");
我不确定XPath语法,但我对LINQ to XML版本很有信心,这本身就是该解决方案的优势所在
您还需要在name
元素上应用前缀,并且需要引用字符串文字:"descendant::d:job[d:name = 'receiverjob']"
。