Reading custom machine.config elements using XmlDocument? - c#

In machine.config file there are elements written there by 3rd party software so it looks like this:
<configuration>
<configSections>
...
</configSections>
...
<Custom>
<Level1> ...
</Level1>
<Level2> ...
</Level2>
<Level3>
<add key="key_text1" value="s1" />
<add key="key_text2" value="s2" />
<add key="key_text3" value="s3" />
</Level3>
</Custom>
</configuration>
I want to get e.g. a value ("s2") of "value" attribute where key="key_text2" from configuration/Custom/Level3 node. So far, I tried to open machine.config as an XML and work from there:
Configuration config = ConfigurationManager.OpenMachineConfiguration();
XmlDocument doc = new XmlDocument();
doc.LoadXml(config.FilePath);
however, I get XmlException "Data at the root level is invalid.". I also don't know how to use Configuration class methods directly to get this done. Any ideas would be appreciated.

Use RuntimeEnvironment.SystemConfigurationFile to get machine.config location:
XmlDocument doc = new XmlDocument();
doc.Load(RuntimeEnvironment.SystemConfigurationFile);
Also why not to use Linq to Xml?
XDocument xdoc = XDocument.Load(RuntimeEnvironment.SystemConfigurationFile);
var element = xdoc.XPathSelectElement("//Custom/Level3/add[#value='s2']");
if (element != null)
key = (string)element.Attribute("key");

Try using the Load() method instead of LoadXml()
doc.Load(config.FilePath);
I also sould suggest you have a look at XDocument instead of XmlDocument. LINQ will really be of use when getting that value from the config file.

Related

How to get parent node's attribute value by using child node's attribute value in xmldocument?

I had xml like following:
<Root Details="false">
<Product count="45" Name="Success">
<Source Id="123" Name="58372">
<Project Id="ABC" Level = "Good">
<Rest of the document/>
</Project>
</Source>
<Source Id="456" Name="83729">
<Project Id="DEF" Level = "Better">
<Rest of the document/>
</Project>
</Source>
<Source Id="789" Name="29832">
<Project Id="GHI" Level = "BAD">
<Rest of the document/>
</Project>
</Source>
</Product>
</Root>
I need to get values of Source node's "Name" value by using Project node's "Id" attribute value. i.e. For Example If project id value is "GHI" then I need value "29832". Is there any way to get like this?
Have you looked into LINQ's XDocument and XElement classes? The code would be something like (I'm on my phone so doing this from memory):
var doc = XDocument.Load("your file.xml");
var sourceName = doc.Root.Elements("Project").Where(p => p.Attribute("Id").value == "GHI").First().Parent.Attribute("Name").value;
Every xelement has a parent property.

how to modify xml node using c#

have that xml file :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<applicationSettings>
<AllSettings>
<setting name="setting1" serializeAs="String">
<value>myValue</value>
</setting>
</AllSettings>
</applicationSettings>
</configuration>
and i want to change the value of <value> into something else, i have tried a couple method but can't find attribute <value>
You can use XElement.ReplaceWith:
XDocument doc = XDocument.Load("data.xml");
XElement value = doc.Root.Descendants("value").SingleOrDefault();
value.ReplaceWith(new XElement("value", "newValue"));
doc.Save("data.xml");
or, as the other answer suggested, XElement.SetValue:
value.SetValue("newValue");
You can load your XML in a XDocument object (System.Xml.Linq namespace) and then change the value like this:
// load XML from string:
var xdoc = XDocument.Parse(xml);
// or load XML from file:
var xdoc = XDocument.Load("filename.xml");
// change value
xdoc.Root.Element("applicationSettings").Element("AllSettings").Element("setting").Element("value").SetValue("myNewValue");

C# update deeply nested XML element value [duplicate]

This question already has answers here:
C# applicationSettings: how to update app.config?
(4 answers)
Closed 8 years ago.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
...
<connectionStrings>
...
</connectionStrings>
<applicationSettings>
<Settings>
...
<setting name="ServerConfig" serializeAs="String">
<value>STAGE</value>
</setting>
...
</Settings>
</applicationSettings>
</configuration>
I have the above XML structure, and for testing purposes I'm trying to throw together an app that will change the ServerConfig value element to be a different string (STAGE, PRODUCTION, INTERNAL). I'm unsure how to navigate to and update that value.
Edit:
XmlDocument xml = new XmlDocument();
xml.Load("doc.xml");
foreach (XmlElement element in xml.SelectNodes("setting"))
{
foreach (XmlElement child in element)
{
if (element.SelectSingleNode("value").InnerText == "STAGE")
{
MessageBox.Show(child.InnerText);
}
}
}
This is the code I've been trying to get to work, but can't seem to get the value. I want to be able to select the setting with the name attribute "ServerConfig" and change the value of the value element.
I recommend using the Slow Cheetah Visual Studio extension. It lets you modify your app settings for each individual build definition using xml transforms.
You can find more information about Slow Cheetah here

Extracting App version number from XML with C#

I have an XML file as follows. I would like to extract the Version number from this file.
I tried XML parsing. But, that is for node values only. I am able to get this file as string as follows. var doc = XDocument.Load("WMAppManifest.xml");
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
<DefaultLanguage xmlns="" code="en-US" />
<App xmlns="" ProductID="{a3f55b1e-c183-4645-9b19-87a41a206978}" Title="sometitle" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="M-Files author" BitsPerPixel="32" Description="Apache Cordova for Windows Phone" Publisher="CordovaExample" PublisherID="{b93a0d8e-5aa9-4d9b-b232-17e2d852e779}">
<IconPath IsRelative="true" IsResource="false">ApplicationIcon.png</IconPath>
</App>
</Deployment>
You can access the XML declaration node as follows:
XmlDeclaration declaration = doc.ChildNodes
.OfType<XmlDeclaration>()
.FirstOrDefault();
You can then read the value of declaration.Version.
Or, if you are after the 'app' version attribute in the XML document itself, try the following
string version = doc.Descendants("App")
.Single()
.Attribute("Version").Value

Getting section filtering to xml attribute

I want to select SMS section block according to tip attribute of SMS xml.
Currently: ConfigurationManager.GetSection("Logger/Sms") works but is there any way to get section like ConfigurationManager.GetSection("Logger/Sms[#tip='VF']")?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="Logger">
<section name="Sms" type="caSectionTest.LogHandler, caSectionTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</sectionGroup>
</configSections>
<Logger>
<Sms tip="Clickatell">
<icerik>Soğuk zincir uygulamasından gönderilen sms</icerik>
<telNo>9053123123123</telNo>
<api>3363050</api>
<user>pkUser</user>
<pass>passhm</pass>
</Sms>
<Sms tip="Vodafone">
<icerik>write something into sms</icerik>
<telNo>905123123123</telNo>
<originator>336123</originator>
<user>ctUser</user>
<pass>9Mdfpass</pass>
</Sms>
</Logger>
</configuration>
You've probably long since moved on, but I created an XPath lookup for xml XElement recently available here: https://github.com/ChuckSavage/XmlLib/ If you want to use jsobo's comment to get the information you want.
You would use it like:
XElement root = XElement.Load(file);
XElement sms = root.XPathElement("//Sms[#tip={0}]", "VF"); // or "//Sms[#tip='VF']"
By using it with string.Format() syntax, you pass the type to the XPath as well, if you wanted to do a DateTime check, etc. I also find it easier for variable injections as well, instead of "//Sms[#tip='" + variable + "']". XPathElement is just XPath().FirstOrDefault() to return a single element.

Categories

Resources