Re: XML adding a node in C#
- From: "Chris Lovett" <someone@xxxxxxxxxxxxx>
- Date: Tue, 7 Jun 2005 21:56:05 -0700
There's a much easier way.
// Load the machine.config file into the XML document
Uri baseUri = new Uri(typeof(string).Assembly.Location);
Uri uri = new Uri(baseUri, "config\\machine.config");
XmlDocument doc = new XmlDocument();
doc.Load(uri.AbsolutePath);
Then use XPath to find what you want:
// Finds the right node and change it to the new value.
XmlNode node =
doc.SelectSingleNode("configuration/appSettings/add[@key = 'ServerName']");
if (node != null) {
Console.WriteLine(node.InnerText);
}
"Keith M" <keith.mallett@xxxxxxxxxxxxxxxx> wrote in message
news:42a55b9d$1_1@xxxxxxxxxxxxxxxxxxxxxxxxx
> Hi,
>
> I have found a very useful piece of code in the msdn which shows how to
> load
> an xml config file, search for a particular value and replace it.
> Could someone possibly convert it to C# from the VB I have?
> I also would like to use similar code to update the machine.config file so
> if someone could explain how to add a node ("appSettings") if node not
> found
> and also how to add a key value pair into the "appSettings" node if found
> I
> would be extremely grateful.
>
> The code snippet I have from msdn is as follows
>
> ' Loads the config file into the XML DOM.
> Dim XmlDocument As New System.Xml.XmlDocument()
> XmlDocument.Load(FileInfo.FullName)
>
> ' Finds the right node and change it to the new value.
> Dim Node As System.Xml.XmlNode
> Dim FoundIt As Boolean = False
> For Each Node In XmlDocument.Item("configuration").Item("appSettings")
> If Node.Name = "add" Then ' skip any comments
> If Node.Attributes.GetNamedItem("key").Value = "ServerName" Then
> Node.Attributes.GetNamedItem("value").Value = ProvidedName
> FoundIt = True
> End If
> End If
> Next Node
>
>
>
> Apologies if this is the wrong group, I am happy to repost to a more
> correct
> one if someone can point me the way.
>
> --
> KM
>
>
>
>
>
.
- Follow-Ups:
- Re: XML adding a node in C#
- From: Keith M
- Re: XML adding a node in C#
- References:
- XML adding a node in C#
- From: Keith M
- XML adding a node in C#
- Prev by Date: RE: XmlDocument.SelectSingleNode() & namespaces - doesn't work
- Next by Date: Re: Serialize XML With Attributes Instead of Elements
- Previous by thread: XML adding a node in C#
- Next by thread: Re: XML adding a node in C#
- Index(es):
Relevant Pages
|