xml(带有命名空间的)读写操作

xml文件:





true



EmailBDOTrigger_2
EmailBDOTrigger_2
EmailBDOTriggerGroup_2
EmailBDOJob_2
1-2 1-3 1-3 * * ?


 

后台:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;

namespace CronMaker
{
class XMLHandler 
{
string xmlPath = @"..\..\quartz_jobs.xml";
//string xmlPath = HttpContext.Current.Server.MapPath("~/quartz_jobs.xml");

private String txtcorn;
public XMLHandler(String txtcorn)
{
this.txtcorn = txtcorn;
}

public void changNode()
{
//XmlTextReader tReader = new XmlTextReader("\\quartz_jobs.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Normalize();
xmlDoc.Load(xmlPath);
//xml中有命名空间
XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDoc.NameTable);
xnm.AddNamespace("mxh", "http://quartznet.sourceforge.net/JobSchedulingData");
string XPath = @"/mxh:job-scheduling-data/mxh:schedule/mxh:trigger/mxh:cron";

XmlNodeList nodes = xmlDoc.SelectSingleNode(XPath, xnm).ChildNodes; 
foreach (XmlNode item in nodes)
{
// XmlElement element = item as XmlElement;
// Console.WriteLine(element.InnerText);
//if (element.Name == "cron-expression")
// element.InnerText = txtcorn;
if (item.Name == "cron-expression")
item.InnerText = txtcorn;
}
xmlDoc.Save(xmlPath);
}
public void addNode()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Normalize();
xmlDoc.Load(xmlPath);
XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDoc.NameTable);
xnm.AddNamespace("mxh", "http://quartznet.sourceforge.net/JobSchedulingData");
string XPath = @"/mxh:job-scheduling-data/mxh:schedule";
XmlNode root = xmlDoc.SelectSingleNode(XPath, xnm);

// XmlNode root = xmlDoc.SelectSingleNode("job-scheduling-data/schedule");

XmlElement trigger = xmlDoc.CreateElement("trigger",xmlDoc.DocumentElement.NamespaceURI);
XmlElement corn = xmlDoc.CreateElement("cron", xmlDoc.DocumentElement.NamespaceURI);
//加入name节点
XmlElement sub1 = xmlDoc.CreateElement("name", xmlDoc.DocumentElement.NamespaceURI);
sub1.InnerText = "EmailBDOTrigger_2";
corn.AppendChild(sub1);
//group节点
XmlElement sub2 = xmlDoc.CreateElement("group", xmlDoc.DocumentElement.NamespaceURI);
sub2.InnerText = "EmailBDOTrigger_2";
corn.AppendChild(sub2);
//job-name节点
XmlElement sub3 = xmlDoc.CreateElement("job-name", xmlDoc.DocumentElement.NamespaceURI);
sub3.InnerText = "EmailBDOTriggerGroup_2";
corn.AppendChild(sub3);
//job-group节点
XmlElement sub4 = xmlDoc.CreateElement("job-group", xmlDoc.DocumentElement.NamespaceURI);
sub4.InnerText = "EmailBDOJob_2";
corn.AppendChild(sub4);
//cron-expression节点
XmlElement sub5 = xmlDoc.CreateElement("cron-expression", xmlDoc.DocumentElement.NamespaceURI);
sub5.InnerText = txtcorn;
corn.AppendChild(sub5);

trigger.AppendChild(corn);
//问题所在:在AppendChildren,如果ParentNode是带有xmlns属性的,在新加节点时如果不指定xmlns或指定为空时,子节点将出现xmlns=""属性
//解决:不是没有为子节点指定命名空间,而是应该为其指定与父节点相同的命名空间
root.AppendChild(trigger);

xmlDoc.Save(xmlPath);
}

}
}

转载于:https://www.cnblogs.com/smart-can/p/4478681.html

你可能感兴趣的:(xml(带有命名空间的)读写操作)