[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

How to add an element and remove an element in a XML file?

Basically, I would like to know how to add or remove an elemet from the XML file below using VB .Net:

<?xml version="1.0" standalone="yes"?>
<RECORD>
  <TYPE>
    <TIME_STARTED>4:44</TIME_STARTED>
     <TIME_ENDED>6:33</TIME_ENDED>
</TYPE>
</RECORD>

When the 'TODAY' element is added the XML file would look like this:

<?xml version="1.0" standalone="yes"?>
<RECORD>
  <TYPE>
    <TODAY>Oct. 26 2004</TODAY>
    <TIME_STARTED>4:44</TIME_STARTED>
     <TIME_ENDED>6:33</TIME_ENDED>
</TYPE>
</RECORD>

And when the "TODAY' element is removed it would look like the first XML file in this question.

Thanks

0
Richard Kreidl
Asked:
Richard Kreidl
  • 2
1 Solution
 
UncleMidriffCommented:
This code will do what you need, I think.  Let me know if I missed something or the point completely ;)  .
_____________________________________________________________________________
        Dim Path As String = Application.StartupPath & "\XMLTest.xml"
        Dim XMLDoc As New Xml.XmlDocument
        Dim RecordNode As Xml.XmlNode
        Dim TodayNode As Xml.XmlNode
        Dim i As Integer

        XMLDoc.Load(Path)

        RecordNode = XMLDoc.ChildNodes(1)

        'remove today nodes
        For i = 0 To RecordNode.ChildNodes.Count - 1
            TodayNode = RecordNode.ChildNodes(i).Item("TODAY")
            RecordNode.ChildNodes(i).RemoveChild(TodayNode)
        Next

        'add today nodes
        For i = 0 To RecordNode.ChildNodes.Count - 1
            TodayNode = XMLDoc.CreateNode(Xml.XmlNodeType.Element, "TODAY", "")
            TodayNode.InnerText = CStr(Now())
            RecordNode.ChildNodes(i).PrependChild(TodayNode)
        Next

        XMLDoc.Save(Application.StartupPath & "\XMLTestResultingFile.xml")
0
 
iboutchkineCommented:
the easiest way is to save xml file to dataset and then add/remove records in dataset. After that save ds to xml
0
 
UncleMidriffCommented:
That's a good idea as well.  But if he did that and removed the column corresponding to "TODAY," would it remove every <TODAY></TODAY> element in the XML file, or would he be able to specify to leave some of the <TODAY></TODAY> elements and delete others?
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now