问题
I am new to XPath. I read the entire W3Schools tutorial. I would like to get all the <schedule>
nodes of my document. I can get all the child elements of my document with child::*
but as soon as I add <schedule>
like the following, I get zero results:
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNodeList jobElements = dom.DocumentElement.SelectNodes("child::schedule");
This is my 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>
</schedule>
</job-scheduling-data>
What I would ultimately like to achieve is to get all the <name>
s of the <job>
s that match a string.
回答1:
That's because your XML has default namespace :
xmlns="http://quartznet.sourceforge.net/JobSchedulingData"
Register a prefix that points to default namespace, then use that prefix along with the element's local name to reference an element in namespace :
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNamespaceManager nsManager = new XmlNamespaceManager(dom.NameTable);
nsManager.AddNamespace("d", dom.DocumentElement.NamespaceURI);
XmlNodeList jobElements = dom.DocumentElement.SelectNodes("child::d:schedule", nsManager);
.NET fiddle demo
回答2:
You could use the following code to find all schedule elements.
XmlDocument dom = new XmlDocument();
dom.Load(textBoxFilePath.Text);
XmlNodeList jobElements = dom.GetElementsByTagName("schedule");
来源:https://stackoverflow.com/questions/26179677/selectnodes-does-not-return-the-child-values