c# - How to create a xmlnode as in given format in asp.net web.config file -
i want add new rule in web.config file programmatically, not able , error
"system.exception: expression must evaluate node-set.".
my code follows..
xmldocument doc = new xmldocument(); bool change = false; string configfile = path.combine( server.mappath("~").tostring(), "web.config"); doc.load(configfile); xmlnode xmlnode1 = cfg.xmlsection.selectsinglenode("rewriterules"); xmlnode xmlnode = xmlnode1.selectsinglenode("rule"); if (xmlnode != null) { string nodeformat = string.format("<rule source='{0}' destination='{1}' />", source, destination); try { xmlelement xmlelement = (xmlelement)(xmlnode.selectsinglenode(nodeformat));//error occured if (xmlelement != null) { //xmlelement.setattribute("source", source); //xmlelement.setattribute("destination", destination); //xmlnode.appendchild(xmlelement); } else { xmlelement = doc.createelement("rule"); xmlelement.setattribute("source", source); xmlelement.setattribute("destination", destination); xmlnode.appendchild(xmlelement); } doc.save(configfile); //savewebconfig( xmldoc ); } catch (exception ex) { throw new exception(ex.message); } please me...
can not use linq xml? it's easier querying/updating xml files.
for example, have method query xml , return true/false if element exists depending on source , destination attributes
public static bool ruleexists(string source, string destination) { xdocument doc = xdocument.load(httpcontext.current .server.mappath("your file")); return doc.descendants("rewriterules").elements() .where(e => e.attribute("source").value == source && e.attribute("destination").value == destination).any(); } this tell if rule exists. modify existing code this:
xdocument xml = xdocument.load(httpcontext.current.server.mappath("your file")); //replace actual source/destination if (ruleexists("about/about-ashoka", "about/about.aspx")) { //element in config file //do something... } else { xelement elem = new xelement("rule"); elem.setattributevalue("source", source); elem.setattributevalue("destination", destination); xml.element("rewriterules").add(elem); xml.save(httpcontext.current.server.mappath("your file")); }
Comments
Post a Comment