There are two input Xelement provides: the first one doesn’t exist in the source and the other one exists but with different attribute values. The output file will have all the existing elements and will include the updated values provided in inputs.
I have a situation where I need to output logs generated by a specific class in a separate file. And there are lots of services in which it needs to be changed across many machines. So I need a utility which can do so programatically. We basically need to add an appender and a logger to all log4net configuration files.
I will specifically focus on how to change config files, this is part of a larger utility.
- <loggername="LoggerName">
- <levelvalue="DEBUG" />
- <appender-refref="ConsoleAppender" />
- </logger>
- First we create XmlDocument from the input string. And then we extract attributes which needs to be updated.
- privatevoid AppendConfigLog4net(string text1nput)
- {
- text1nput = ClearTextFromInvalidChars(text1nput);
- XDocument xmlDoc1 = XDocument.Parse(text1nput, LoadOptions.None);
- foreach (var v1 in xmlDoc1.Descendants())
- {
- if (string.Compare(v1.Name.LocalName, "appender", true) == 0)
- {
- AddAndReplaceAppenderElementInExisitngConfig(v1, v1.Attribute("name").Value, v1.Element("file").Attribute("value").Value);
- }
- elseif (string.Compare(v1.Name.LocalName, "logger", true) == 0)
- {
- AddorReplaceLoggerElementInExisitngConfig(v1, v1.Attribute("name").Value, v1.Element("appender-ref").Attribute("ref").Value);
- }
- }
- }
- privatevoid AddorReplaceLoggerElementInExisitngConfig(XElement v1, string localName, string value)
- {
- var query = from c in xDoc.Root.Descendants("logger")
- where(string) c.Attribute("name") == localName
- select c;
- if (query.Count() <= 0)
- {
- var v2 = xDoc.Root.Descendants("logger").LastOrDefault();
- xDoc.Root.Add(newXElement(v1));
- } else foreach(XElement node in query)
- {
- if ((string) node.Element("appender-ref").Attribute("ref") != value)
- {
- node.Element("appender-ref").Attribute("ref").Value = value;
- }
- }
- }
Pradeep SahooPosted Apr 24, 2016, 12:24 AM
Nice Information .Thanks for sharing