• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 245
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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