12 Replies - 857 Views - Last Post: 12 April 2016 - 12:29 PM Rate Topic: -----

#1 retched   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 25-January 16

Reading an XML file...

Posted 11 April 2016 - 07:56 PM

I might be going about this XML reading/writing the wrong way... I'm trying to create a configuration file in XML as opposed to .INI or a registry edit. Here is the XML file (too big to list here). I'm reading through various documents about how to read XML using XDocument or the system XML reader over LINQ... but those seem to be relating to a database-like set of entries in XML as opposed to what I'm doing. (References used: MSDN document, Net Informations, etc.)

Is there a way for me to read an XML file like this... Or should I possible consider another way to write this configuration XML file.

Is This A Good Question/Topic? 0
  • +

Replies To: Reading an XML file...

#2 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6552
  • View blog
  • Posts: 26,565
  • Joined: 12-December 12

Re: Reading an XML file...

Posted 11 April 2016 - 11:31 PM

Your XML has around 200 lines, which is a small number, so please copy it here between code tags so that we can see what is being discussed.

I'm not sure what your issue is though; you'd examine, and navigate, your file like any other, it just happens to be simpler than other XML documents.
Was This Post Helpful? 0
  • +
  • -

#3 retched   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 25-January 16

Re: Reading an XML file...

Posted 11 April 2016 - 11:39 PM

Can't edit my original post so here's the original XML dump.

My issue is that the methods listed don't necessarily allow me to go Property->Name, Sounds->GeneralSounds->GameIntro like I wanted to unless there's something that I missed.

<?xml version="1.0" encoding="UTF-8"?>
<SoundConfig>
    <Property>
        <Name></Name>
        <Version>1.0</Version>
    </Property>
    <Sounds>
        <GeneralSounds>
            <GameIntro></GameIntro>
            <ContestantIntro></ContestantIntro>
            <ExplainTheRules></ExplainTheRules>
            <CommOutro></CommOutro>
            <CommIntro></CommIntro>
            <ShuffleRd2></ShuffleRd2>
            <ContestantExit></ContestantExit>
            <OutofTime></OutofTime>
            <CreditsOutro></CreditsOutro>
            <AnswerReveal></AnswerReveal>
            <ClockOutOfTime></ClockOutOfTime>
        </GeneralSounds>
        <AskTheAudience>
            <Activate></Activate>
            <Running></Running>
            <Reveal></Reveal>
        </AskTheAudience>
        <FiftyFifty>
            <Activate></Activate>
            <Reveal></Reveal>
        </FiftyFifty>
        <PhoneAFriend>
            <Activate></Activate>
            <Running></Running>
            <End></End>
            <EarlyEnd></EarlyEnd>
        </PhoneAFriend>
        <PlusOne>
            <Activate></Activate>
            <Running></Running>
            <End></End>
        </PlusOne>
        <DoubleDip>
            <Activate></Activate>
            <FinalAnswer1></FinalAnswer1>
            <Answer1Wrong></Answer1Wrong>
            <FinalAnswer2></FinalAnswer2>
        </DoubleDip>
        <SwitchTheQuestion>
            <Activate></Activate>
            <Running></Running>
        </SwitchTheQuestion>
        <JumpTheQuestion>
            <Activate></Activate>
            <Reveal></Reveal>
        </JumpTheQuestion>
        <AskTheExperts>
            <Activate></Activate>
            <Running></Running>
            <End></End>
        </AskTheExperts>
        <CrystalBall>
            <Activate></Activate>
            <Reveal></Reveal>
        </CrystalBall>
        <QuestionSoundEffects>
            <RevealQuestion></RevealQuestion>
            <RevealChoices></RevealChoices>
        </QuestionSoundEffects>
        <MoneyTree>
            <Reveal></Reveal>
            <FlashOver></FlashOver>
            <FlashOverRd2></FlashOverRd2>
            <ShuffleMoneyTree></ShuffleMoneyTree>
            <Lifeline1></Lifeline1>
            <Lifeline2></Lifeline2>
            <Lifeline3></Lifeline3>
            <Lifeline4></Lifeline4>
            <Lifeline5></Lifeline5>
        </MoneyTree>
        <Question_1>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_1>
        <Question_2>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_2>
        <Question_3>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_3>
        <Question_4>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_4>
        <Question_5>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_5>
        <Question_6>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_6>
        <Question_7>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_7>
        <Question_8>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_8>
        <Question_9>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_9>
        <Question_10>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_10>
        <Question_11>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_11>
        <Question_12>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_12>
        <Question_13>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_13>
        <Question_14>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_14>
        <Question_15>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_15>
        <Question_16>
            <LightsDown></LightsDown>
            <QuestionBed></QuestionBed>
            <FinalAnswer></FinalAnswer>
            <CorrectAnswer></CorrectAnswer>
            <WrongAnswer></WrongAnswer>
            <RevealAmount></RevealAmount>
        </Question_16>
    </Sounds>
</SoundConfig>

Was This Post Helpful? 0
  • +
  • -

#4 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6552
  • View blog
  • Posts: 26,565
  • Joined: 12-December 12

Re: Reading an XML file...

Posted 12 April 2016 - 12:15 AM

I would consider using XPath so that you can use expressions like /Sounds/GeneralSounds/GameIntro. XPath can be used with (combined with) other XML classes/approaches.

Typically, XPath returns a node iterator, a collection, but you can use methods such as SelectSingleNode if you only expect a single node to be returned.

How to query XML with an XPath expression
Was This Post Helpful? 1
  • +
  • -

#5 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6552
  • View blog
  • Posts: 26,565
  • Joined: 12-December 12

Re: Reading an XML file...

Posted 12 April 2016 - 12:34 AM

It is quite a common approach though (and not wrong) to use a method that returns a node list, check that it succeeded, and then read the first node returned (or iterate them) even though there will only be one item. Of course, if more than one item is returned, then you know that something has gone wrong with the XML, as you are only expecting a single item.
Was This Post Helpful? 1
  • +
  • -

#6 retched   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 25-January 16

Re: Reading an XML file...

Posted 12 April 2016 - 01:16 AM

Okay I'm slowly getting somewhere with this... Here's what I did, I turned it into a function.

Note: I used the .ToString method because if I left off, it returned a weird value. XPathExpression will be replaced with the value of the selected desired and filename of course refers to a file name referenced by a OpenFile Dialog. (So I shouldn't have to check to see if the file exists, because the Open File dialog has been configured to check if the file exists first hand.)

    Public Function ReturnXMLValue(filename As String, XPathExpression As String) As String

        Dim nav As XPathNavigator
        Dim docNav As XPathDocument
        Dim result As String = ""

        docNav = New XPathDocument(filename)
        nav = docNav.CreateNavigator

        Try
            result = nav.SelectSingleNode(XPathExpression).ToString
        Catch ex As Exception
            result = ""
        End Try

        Return result


    End Function



Is there something that I missed or should also include for this? I'm only interested in the first result found from the search of the XPath.

This post has been edited by retched: 12 April 2016 - 01:28 AM

Was This Post Helpful? 0
  • +
  • -

#7 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6552
  • View blog
  • Posts: 26,565
  • Joined: 12-December 12

Re: Reading an XML file...

Posted 12 April 2016 - 01:42 AM

What happens when you use your function and what values are you providing it with?
Was This Post Helpful? 0
  • +
  • -

#8 retched   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 25-January 16

Re: Reading an XML file...

Posted 12 April 2016 - 01:47 AM

View Postandrewsw, on 12 April 2016 - 03:42 AM, said:

What happens when you use your function and what values are you providing it with?


The function is going to be given the XML filename location (first parameter), and the XML path to search for (second parameter).

Essentially, "Go open this file, and search for this path). The function is being called so that it populates a TextBox in another field that uses the value pulled up.

One small problem, that I just thought about... what happens if someone tries to load a file... does so... and it's not a valid result. (For example, the "root" is missing.... like I just tested...)

Right now the code I have towards this is:
    Private Sub OpenPlaylistToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenPlaylistToolStripMenuItem.Click
        If OpenXMLFileDialog.ShowDialog = DialogResult.OK Then

            Try
                Dim xd1 As XDocument = New XDocument
                xd1 = Xdocument.Load(OpenXMLFileDialog.FileName)
            Catch ex As Exception
                MessageBox.Show("You tried to load an invalid configuration file. Please check the file to see that it is valid and try again. If you continue to see this message, then your file is likely not a valid XML file and cannot be read by the program.")
            End Try

            txtPlaylistName.Text = ReturnXMLValue(OpenXMLFileDialog.FileName, "/SoundConfig/Property/Name")
            ' Repeat the above line about 100 and change times... Yes it's a LOT of names being referenced.

        End If
    End Sub

This post has been edited by retched: 12 April 2016 - 01:51 AM

Was This Post Helpful? 0
  • +
  • -

#9 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6552
  • View blog
  • Posts: 26,565
  • Joined: 12-December 12

Re: Reading an XML file...

Posted 12 April 2016 - 02:01 AM

If the XML is invalid then heads should roll and the integrity of the universe is brought into question.

I'll leave you to check, but I think most of the Load methods raise an Exception if the file is invalid. But I should be using the term malformed rather than invalid. There are ways to check if an XML document is invalid; that is, doesn't comply with a schema. Malformed means it is broken, an invalid document isn't necessarily broken, it just doesn't match what is expected.

Quote

Right now the code I have towards this is:

If the document is malformed then issue a message, as you are, and don't attempt any further processing, just exit the sub (or application).
Was This Post Helpful? 1
  • +
  • -

#10 retched   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 48
  • Joined: 25-January 16

Re: Reading an XML file...

Posted 12 April 2016 - 02:25 AM

Correct, I should using be using the term malformed too. I figured out that using the Xdocument.Load line checks to see if the file is in fact malformed or not. If it does, then it trigger the ex block as written above. So this in theory is good... (Unless someone writes a bad bit of data in that XML file... then I have to see if WMPLib.dll checks to see if its valid. But that's actually for another thread.)

So as I have it now... the Open file sub looks like this:

        If OpenXMLFileDialog.ShowDialog = DialogResult.OK And OpenXML(OpenXMLFileDialog.FileName) Then

            ' Pre-load all the values of the file into the appropriate textboxes.
            txtPlaylistName.Text = ReturnXMLValue(OpenXMLFileDialog.FileName, "/SoundConfig/Property/Name")


        End If


And the new XMLReader module now contains two functions. One to open the file and see if it is valid... the other to actually pull up the data... which should be good now.

    Public Function OpenXML(filename As String)

        Dim result As Boolean = True

        Try
            Dim xd1 As XDocument = New XDocument
            xd1 = Xdocument.Load(filename)
        Catch ex As Exception

            ' This will send the error information to the clipboard

            Clipboard.SetText(ex.ToString, TextDataFormat.Text)

            ' This will display an error message to the user.
            MessageBox.Show("You tried to load an invalid file. Please check the file to see that it is valid and try again. If you continue to see this message, then your file is likely not a valid XML file and cannot be read by the program. " & vbNewLine & vbNewLine & "If you plan on creating a bug report, be sure to describe what you were doing and include the file that you tried to load and the following information:" & vbNewLine & vbNewLine & ex.ToString & vbNewLine & vbNewLine & "The above error message has been copied to the clipboard.", "Invalid File Loaded")

            ' There was an error... This should return a False statement.
            result = False
        End Try

        Return result
    End Function
    Public Function ReturnXMLValue(filename As String, XPathExpression As String) As String

        Dim nav As XPathNavigator
        Dim docNav As XPathDocument
        Dim result As String

        ' Catch any errors relating to it not being a valid document.
        Try
            docNav = New XPathDocument(filename)
            nav = docNav.CreateNavigator
        Catch ex As Exception
            result = ""
        End Try

        ' Catch any errors relating to it not find a particular XML Path.
        Try
            result = nav.SelectSingleNode(XPathExpression).ToString
        Catch ex As Exception
            result = ""
        End Try

        Return result
    End Function


This post has been edited by retched: 12 April 2016 - 02:28 AM

Was This Post Helpful? 0
  • +
  • -

#11 ybadragon   User is offline

  • Home Owner
  • member icon

Reputation: 571
  • View blog
  • Posts: 2,647
  • Joined: 11-May 12

Re: Reading an XML file...

Posted 12 April 2016 - 11:59 AM

It would be even easier to parse out if you know the schema, you can just create a class (or multiple classes) modeled after each of the nodes, then use a serializer to de-serialize the data into the objects.
Was This Post Helpful? 0
  • +
  • -

#12 andrewsw   User is offline

  • RequestedRangeNotSatisfiable
  • member icon

Reputation: 6552
  • View blog
  • Posts: 26,565
  • Joined: 12-December 12

Re: Reading an XML file...

Posted 12 April 2016 - 12:25 PM

We can even create the schema and then the class(es) using xsd.exe. Or even paste XML as classes.. EDIT > Paste Special > Paste XML As Classes.

Generate C# class from XML
Was This Post Helpful? 0
  • +
  • -

#13 ybadragon   User is offline

  • Home Owner
  • member icon

Reputation: 571
  • View blog
  • Posts: 2,647
  • Joined: 11-May 12

Re: Reading an XML file...

Posted 12 April 2016 - 12:29 PM

Ah, I didn't realize that xsd.exe worked for VB.Net classes. I used it at my previous job for generating c#.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1