2017-07-10 150 views
1

這是XML文件,我想爲「cron-expression」獲取Xpath,實際上我想更改內部文本。我嘗試過很多方法,但沒有任何效果,我只想得到直接的答案。 我曾嘗試像本地名稱和XmlnamespaceManager.addnamespace,但它不起作用。 C#XML XPATH與命名空間

<!-- This file contains job definitions in schema version 2.0 format --> 

<job-scheduling-data 
xmlns="http://quartznet.sourceforge.net/JobSchedulingData" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> 

    <processing-directives> 
    <overwrite-existing-data>true</overwrite-existing-data> 
    </processing-directives> 

    <schedule> 

    <job> 
     <name>SampleJob</name> 
     <group>SampleGroup</group> 
     <description>My job</description> 
     <job-type>Quartz.Server.SampleJob, Quartz.Server</job-type> 
     <durable>true</durable> 
     <recover>false</recover> 
    </job> 

    <trigger> 
    <cron> 
     <name>SampleTrigger</name> 
     <group>SampleGroup</group> 
     <description>Simple trigger to simply fire sample job</description> 
     <job-name>SampleJob</job-name> 
     <job-group>SampleGroup</job-group> 
     <misfire-instruction>SmartPolicy</misfire-instruction> 
     <cron-expression>0 * 15 * * ?</cron-expression> 
     </cron> 
    </trigger> 
    </schedule> 
</job-scheduling-data> 

這是我的代碼。不行。

protected void Button2_Click(object sender, EventArgs e) 
    { 
     XmlDocument doc = new XmlDocument(); 
     doc.Load("D:/Chrome/Quartz.NET-2.4.1/src/Quartz.Examples/quartz_jobs.xml"); 
     XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable); 
     xnm.AddNamespace("h", 
"http://quartznet.sourceforge.net/JobSchedulingData"); 

    XmlNode XN = doc.SelectSingleNode("h:job-scheduling-data/h:schedule/h:trigger/h:cron/h:cron-expression",xnm); 


//  XmlNode XN = doc.SelectSingleNode("/*[local-name() = 'job-scheduling-data']/*[local-name() = 'schedule']/*[local-name() = 'trigger']/*[local-name() = 'cron']/*[local-name() = 'cron-expression']"); 
    XN.InnerText = "0"; 
    doc.Save("D:/Chrome/Quartz.NET-2.4.1/src/Quartz.Examples/quartz_jobs.xml");// 
} 
+0

什麼方法不起作用(粘貼代碼)? –

+0

@LeiYang使用like/* [local-name ='schedule']/xxxxxx和XmlnamespaceManager.addnamespace –

回答

0

嘗試使用的XDocument - ( 「使用System.Xml.Linq的」)

var doc = XDocument.Load(File.Open("D:/Chrome/Quartz.NET-2.4.1/src/Quartz.Examples/quartz_jobs.xml",FileMode.Open)); 

var childElements = doc.DescendantNodes().Where(n => n.NodeType == XmlNodeType.Element).Select(n => (n as XElement)); 
var cronElement = childElements.Where(e => e.Name.LocalName == "cron-expression").FirstOrDefault(); 
cronElement.SetValue("0"); 

doc.Save("D:/Chrome/Quartz.NET-2.4.1/src/Quartz.Examples/quartz_jobs.xml");