XmlTextWriter question

  • Thread starter Thread starter Karl Hungus
  • Start date Start date
K

Karl Hungus

Is it possible to use XmlTextReader and XmlTextWriter to open an XML file,
search for a particular node, and then append nodes there?

If so, do you have a little code example (c#)?

Thanks in advance,
Karl
 
Karl Hungus said:
Is it possible to use XmlTextReader and XmlTextWriter to open an XML file,
search for a particular node, and then append nodes there?

If so, do you have a little code example (c#)?

Thanks in advance,
Karl

Rather use the XmlDocument object.
In this code (it's in VB, but you'll get the idea),
a new node is added to web.config.

You might have a look into XPath expressions, because that
is what is used here to search for a particular node (in SelectSingleNode)

Try
Dim doc As New XmlDocument()
doc.Load(Server.MapPath("web.config"))

' Search this configuration for the credentials element
Dim strSel As String =
"/configuration/system.web/authentication/forms/credentials"
Dim nodeCredentials As XmlNode = doc.SelectSingleNode(strSel)

' Create a new element with 2 attributes
Dim elNew As XmlElement = doc.CreateElement("user")
Dim attribName As XmlAttribute = doc.CreateAttribute("name")
attribName.Value = "Peter"
Dim attribPassword As XmlAttribute = doc.CreateAttribute("password")
attribPassword.Value = "blabla"
elNew.Attributes.Append(attribName)
elNew.Attributes.Append(attribPassword)

nodeCredentials.AppendChild(elNew)

' Save the configuration
doc.Save(Server.MapPath("web.config"))

Catch ex As Exception
Trace.Warn(ex.ToString())
End Try
 
Back
Top