[Last Call] Learn how to a build a cloud-first strategyRegister Now

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

vb.net - XmlReader

Hi all,
How can I use XmlReader to move to a specific element? Suppose I have 3 elements in my document called and underneath each one of them I have some attributes. How can I move to a specific element and read ONLY attributes under this element? I'm using vb.net.

Thanks!!!
0
nahumba
Asked:
nahumba
  • 6
  • 2
  • 2
1 Solution
 
icrCommented:
By attribute do you mean sub-elements or actual attributes?

Attributes
<node attribute="attributevalue"/>

Sub-Elements
<node>
    <sub-node>value</sub-node>
</node>
0
 
nahumbaAuthor Commented:
Hi icr,
Well actually I'm trying to create an XML file which looks like this:

- <SETTINGS>
  <OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
  <OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
  <OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
  <OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
  </SETTINGS>

<SETTINGS_2>
<OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
<OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
<OSR OBJECT_NAME="asd" INDEX="0" PERMISSIONS="ReadAndExecute" GROUPS="Authenticated Users" />
</SETTINGS_2>

And then simply read the attributes by choise (lets say I would like to read attributes under "SETTINGS_2").
Is it possible?
I can't seem to succeed creating such file..
If you could post the most simplest example of creating and then reading such file, it will be great!

Thank you,
nahumba
0
 
icrCommented:
I'm afraid I can't help you out immediately, but I'm sure someone else will be able to help you soon.
Just a quick note though, a valid XML file must have only one root. So you would want something like:
<PROGRAMSETTINGS>
    <SETTINGS>
        ....
    </SETTINGS>
    <SETTINGS_2>
        ....
    </SETTINGS_2>
</PROGRAMSETTINGS>
0
Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

 
nahumbaAuthor Commented:
Ok icr, thanks. I'd be glad if you check the status of this discussion later on, when you'll have a spare time.

Thank you again!
0
 
AWestEngCommented:
You can create a dataset with the data and write it to an xml file

 Public Sub WriteDataSetToXML(ByVal ds As DataSet, ByVal strXMLPath As String)
        ds.WriteXml(strXMLPath)
    End Sub

    Public Function ReadXMLToDataset(ByVal strXMLPath As String) As DataSet
        Dim ds As DataSet = New DataSet
        ds.ReadXml(strXMLPath)
        Return ds
    End Function
0
 
AWestEngCommented:
Public Sub writedata(ByVal strXMLPath As String, ByVal errorString As ArrayList, _
                                           Optional ByVal Encode As Encoding = Nothing)

        Dim objXMLWriter As XmlTextWriter = Nothing
        Dim infoSettings As String
        Dim i As Integer = 1

        'Create th XML file with all errors from errorstring
        Try
            'Create a new XML file
            objXMLWriter = New XmlTextWriter(strXMLPath, Encode)

            objXMLWriter.WriteStartDocument()
            objXMLWriter.WriteStartElement("errorFile")

            Dim SectionEnumerator As System.Collections.IEnumerator = errorString.GetEnumerator()

            'Write the data from errorString to XML file
            While SectionEnumerator.MoveNext()
                infoSettings = CStr(i)
                objXMLWriter.WriteStartElement("StartAtr")
                objXMLWriter.WriteAttributeString("ID", i.ToString)
                objXMLWriter.WriteAttributeString("Data", SectionEnumerator.Current.ToString)
                objXMLWriter.WriteEndElement()
                'Progressbar counter
                i += 1
                moS.pb1.Value = CInt(((i * 100) / (errorString.Count))) '/ 2))
            End While

            'write the ending tag for configuration
            objXMLWriter.WriteEndElement()
            objXMLWriter.WriteEndDocument()
            'Write the file
            objXMLWriter.Flush()

        Catch e As Exception
            MsgBox( e.ToString, _
                 MsgBoxStyle.Critical, "Error"
            Throw e
        Finally
            'Close the writer
            objXMLWriter.Close()
            objXMLWriter = Nothing
        End Try

    End Sub
0
 
AWestEngCommented:
Public Sub ReadData(ByVal strXMLPath As String)


        Dim objXMLReader As XmlTextReader = Nothing
        Dim arrData() As String
        Dim arrID() As String
        Dim i As Integer = 0

        '****************************************************************************
        '  Count nodes
        '****************************************************************************
        'Declaration of Number of Nodes
        Dim numNode As Integer
        'The path of the setting file
        Dim xmlDoc As New Xml.XmlDocument
        Dim xmlFile As String = strXMLPath

        'Open XML file
        xmlDoc.Load(xmlFile)
        Dim root As Xml.XmlElement = xmlDoc.DocumentElement
        Dim node As Xml.XmlNode

        Try
            'Number of nodes in XML file
            numNode = root.ChildNodes.Count

            'Close everything
            xmlDoc = Nothing
            root = Nothing
            node = Nothing
            xmlFile = Nothing

            '****************************************************************************
            '   Read XML file
            '****************************************************************************
            'Create the XML Reader
            objXMLReader = New XmlTextReader(strXMLPath)
            'Disable whitespace so that you don't have to read over whitespaces
            objXMLReader.WhitespaceHandling = WhitespaceHandling.None
            'read the xml declaration
            objXMLReader.Read()
            'read the TaxiGBG tag
            objXMLReader.Read()

            'Set the size of string Array
            ReDim arrData(numNode - 1)
            ReDim arrID(numNode - 1)

            objXMLReader.Read()

            'if not start element exit function and delete error file
            If Not objXMLReader.IsStartElement() Then
                'close the reader
                objXMLReader.Close()
                objXMLReader = Nothing
                File.Delete(strXMLPath)
                Exit Sub
            End If

            'Load the Loop
            While Not objXMLReader.EOF
                'Get the Attribute Value
                arrData(i) = Trim(objXMLReader.GetAttribute("Date"))
                arrID(i) = Trim(objXMLReader.GetAttribute("ID"))

                'Go to the  next name tag
                objXMLReader.Read()

                'if not start element exit function and delete error file
                If Not objXMLReader.IsStartElement() Then
                    Exit While
                End If
                i += 1
            End While

        Catch exp As Exception

        Finally
            'close the reader
            objXMLReader.Close()
            objXMLReader = Nothing
        End Try
    End Sub
0
 
AWestEngCommented:
The functions can be done a bit nicer, but it can get you started. I hope.
0
 
AWestEngCommented:
Change a value in the xml file, if it dsen't exist create it    

Public Function SetCreateValue(ByVal strKey As String, ByVal strValue As String, ByVal strSection As String) As Boolean
        Dim cfgDoc As XmlDocument = New XmlDocument
        Dim FileFullPath As String
        Dim node As XmlNode

        'The path of the setting file
        FileFullPath = "C:\Settings.xml"

        loadConfigDoc(cfgDoc, FileFullPath)
        ' retrieve the appSettings node
        node = cfgDoc.SelectSingleNode(strSection)

        If (node Is Nothing) Then
            Throw New System.InvalidOperationException(strSection & " Section not found")
        End If

        Try
            ' XPath select setting "add" element that contains this key    
            Dim addElem As XmlElement = CType(node.SelectSingleNode("object[@ key" & "='" & strKey & "']"), XmlElement)
            If (Not addElem Is Nothing) Then
                addElem.SetAttribute("value", strValue)
            Else
                ' not found, so we need to add the element, key and value
                Dim entry As XmlElement = cfgDoc.CreateElement("object")
                entry.SetAttribute("key", strKey)
                entry.SetAttribute("value", strValue)
                node.AppendChild(entry)
            End If
            'save it
            saveConfigDoc(cfgDoc, FileFullPath)
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function
0
 
AWestEngCommented:
   'Load XML file
    Private Function loadConfigDoc(ByVal cfgDoc As XmlDocument, ByVal XMLFile As String) As XmlDocument
        Dim docName As String = String.Empty
        Try
            docName = XMLFile
            cfgDoc.Load(docName) 'Open XML file
            Return cfgDoc
        Catch ex As Exception
            cfgDoc = Nothing
            Throw ex
        End Try
    End Function

    'Save XML file
    Private Sub saveConfigDoc(ByVal cfgDoc As XmlDocument, ByVal cfgDocPath As String)
        Dim writer As XmlTextWriter = Nothing
        Try
            writer = New XmlTextWriter(cfgDocPath, Nothing)
            writer.Formatting = Formatting.Indented
            cfgDoc.WriteTo(writer)
            writer.Flush()

            'If a new object as been added to the form and not saved.
            'Skip ArgumentNullException exceptions
        Catch ArgumentNullException As ArgumentNullException
            Exit Sub
        Catch exp As Exception
        Finally
            writer.Close()
            writer = Nothing
            System.GC.Collect()
        End Try
    End Sub
0

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

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