New to XML. Need help reading XML.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Justin

    New to XML. Need help reading XML.

    Here's my XML:

    <?xml version="1.0" ?>
    <AppMode Type="Network">
    <CurrentFolde r Path="c:\tabs">
    <Tabs>
    <FilePath>tabs\ Justin.tab</FilePath>
    <FilePath>tabs\ Julie.tab</FilePath>
    *****There could be 1 of these or 100....quantity can change*****
    </Tabs>
    </CurrentFolder>
    </AppMode>


    All I need to do is load "Network" and "c:\tabs" into variables. Then each
    FilePath goes into an array.

    The following code gives me everything but Julie.tab. It only gives me one
    of the FilePaths. I'm not even sure if this is the right/best way to do
    this:

    Dim XMLReader As XmlTextReader = New XmlTextReader(" ")
    XMLReader.White spaceHandling = WhitespaceHandl ing.None

    XMLReader.Read( )
    XMLReader.Read( )
    MsgBox(XMLReade r.GetAttribute( "Type"))

    XMLReader.Read( )
    MsgBox(XMLReade r.GetAttribute( "Path"))

    XMLReader.Read( )

    While Not XMLReader.EOF *****Why isn't this looping?

    XMLReader.Read( )

    If Not XMLReader.IsSta rtElement() Then
    Exit While
    End If

    MsgBox(XMLReade r.ReadElementSt ring("FilePath" ))

    End While

    XMLReader.Close ()



    Any help would be greatly appreciated!

  • Martin Honnen

    #2
    Re: New to XML. Need help reading XML.

    Justin wrote:
    Here's my XML:
    >
    <?xml version="1.0" ?>
    <AppMode Type="Network">
    <CurrentFolde r Path="c:\tabs">
    <Tabs>
    <FilePath>tabs\ Justin.tab</FilePath>
    <FilePath>tabs\ Julie.tab</FilePath>
    *****There could be 1 of these or 100....quantity can change*****
    </Tabs>
    </CurrentFolder>
    </AppMode>
    >
    >
    All I need to do is load "Network" and "c:\tabs" into variables. Then
    each FilePath goes into an array.
    One way is to use XPath to find the nodes:

    Dim doc As New XPathDocument(" ..\..\XMLFile1. xml")
    Dim nav As XPathNavigator =
    doc.CreateNavig ator().SelectSi ngleNode("AppMo de")
    Dim type As String = nav.GetAttribut e("Type", "")
    Console.WriteLi ne("Type: {0}", type)
    nav = nav.SelectSingl eNode("CurrentF older")
    Dim path As String = nav.GetAttribut e("Path", "")
    Console.WriteLi ne("Path: {0}", path)
    Dim filePaths As XPathNodeIterat or = nav.Select("Tab s/FilePath")
    Console.WriteLi ne("Found {0} file path(s):", filePaths.Count )
    Dim paths(filePaths .Count) As String
    Dim i As Integer = 0
    For Each filePath As XPathNavigator In filePaths
    paths(i) = filePath.Value
    Console.WriteLi ne(paths(i))
    i = i + 1
    Next


    --

    Martin Honnen --- MVP XML

    Comment

    • Steven Cheng [MSFT]

      #3
      RE: New to XML. Need help reading XML.

      Hi Justin,

      From your description, you want to extract some certain values from an XML
      document. In .net framework, there is quite rich API support for XML query
      and processing. Here you have three different possible means to do it:

      1. Use the xmlreader as you've tried, this is a memory efficient approahc,
      but maybe more difficult to code(when xml is complex)

      2. use XmlDocument + Xpath query, this is quite simple code

      3. If you can use .NET 3.5, then "Linq to XML" is quite a good weapon you
      can utilize

      Here I've produced sample code (extracting the elements you want) for all
      of the 3 approaches mentioned above:

      ===========usin g XML Reader========= =======
      private void btnReader_Click (object sender, EventArgs e)
      {
      StreamReader sr = new StreamReader(@" ..\..\test.xml" ,
      Encoding.UTF8);
      XmlReader xr = XmlReader.Creat e(sr);

      List<stringpath s = new List<string>();

      while (xr.Read())
      {
      if (xr.IsStartElem ent("AppMode"))
      {
      MessageBox.Show (xr.GetAttribut e("Type"));
      }else if(xr.IsStartEl ement("CurrentF older"))
      {
      MessageBox.Show (xr.GetAttribut e("Path"));
      }
      else if (xr.IsStartElem ent("FilePath") )
      {
      paths.Add(xr.Ge tAttribute("Pat h"));
      }
      }

      MessageBox.Show ("paths count: " + paths.Count);
      sr.Close();
      }
      =============== ======

      ========USE XML document + xpath query========== ====
      private void btnXmlDoc_Click (object sender, EventArgs e)
      {
      XmlDocument doc = new XmlDocument();
      doc.Load(@"..\. .\test.xml");

      string type =
      doc.SelectSingl eNode("/AppMode").Attri butes["Type"].Value;
      string curfolder =
      doc.SelectSingl eNode("/AppMode/CurrentFolder") .Attributes["Path"].Value;

      XmlNodeList files = doc.SelectNodes ("//FilePath");

      List<stringpath s = new List<string>();

      foreach (XmlNode pnode in files)
      {
      paths.Add(pnode .InnerText);
      }

      MessageBox.Show ("type: " + type + "\r\n"
      + "current folder: " + curfolder + "\r\n"
      + "paths count: " + paths.Count);


      }
      =============== ===============



      ============ use LINQ TO XML =============== ====
      private void btnLinq_Click(o bject sender, EventArgs e)
      {
      StreamReader sr = new StreamReader(@" ..\..\test.xml" ,
      Encoding.UTF8);
      XDocument xdoc = XDocument.Load( sr);
      sr.Close();


      string type = xdoc.Element("A ppMode").Attrib ute("Type").Val ue;
      var cfs = from cf in xdoc.Descendant s("CurrentFolde r")
      select cf.Attribute("P ath").Value;

      string curfolder = cfs.First();

      var paths = from fp in xdoc.Descendant s("FilePath")
      select fp.Value;

      List<stringfpat hs = paths.ToList();

      MessageBox.Show ("type: " + type + "\r\n"
      + "current folder: " + curfolder + "\r\n"
      + "paths count: " + fpaths.Count);

      }
      =============== ==============

      if you want to know more about LINQ to XML, please have a look at the MSDN
      reference:

      #.NET Language-Integrated Query for XML Data


      Sincerely,

      Steven Cheng

      Microsoft MSDN Online Support Lead


      Delighting our customers is our #1 priority. We welcome your comments and
      suggestions about how we can improve the support we provide to you. Please
      feel free to let my manager know what you think of the level of service
      provided. You can send feedback directly to my manager at:
      msdnmg@microsof t.com.

      =============== =============== =============== =====
      Get notification to my posts through email? Please refer to
      Gain technical skills through documentation and training, earn certifications and connect with the community

      ications.

      Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
      where an initial response from the community or a Microsoft Support
      Engineer within 1 business day is acceptable. Please note that each follow
      up response may take approximately 2 business days as the support
      professional working with you may need further investigation to reach the
      most efficient resolution. The offering is not appropriate for situations
      that require urgent, real-time or phone-based interactions or complex
      project analysis and dump analysis issues. Issues of this nature are best
      handled working with a dedicated Microsoft Support Engineer by contacting
      Microsoft Customer Support Services (CSS) at
      http://msdn.microsoft.com/subscripti...t/default.aspx.
      =============== =============== =============== =====
      This posting is provided "AS IS" with no warranties, and confers no rights.
      --------------------
      >From: "Justin" <None@None.co m>
      >Subject: New to XML. Need help reading XML.
      >Date: Sat, 26 Jul 2008 00:24:30 -0700
      >
      >Here's my XML:
      >
      ><?xml version="1.0" ?>
      ><AppMode Type="Network">
      ><CurrentFold er Path="c:\tabs">
      ><Tabs>
      ><FilePath>tabs \Justin.tab</FilePath>
      ><FilePath>tabs \Julie.tab</FilePath>
      >*****There could be 1 of these or 100....quantity can change*****
      ></Tabs>
      ></CurrentFolder>
      ></AppMode>
      >
      >
      >All I need to do is load "Network" and "c:\tabs" into variables. Then
      each
      >FilePath goes into an array.
      >
      >The following code gives me everything but Julie.tab. It only gives me
      one
      >of the FilePaths. I'm not even sure if this is the right/best way to do
      >this:
      >
      >Dim XMLReader As XmlTextReader = New XmlTextReader(" ")
      >XMLReader.Whit espaceHandling = WhitespaceHandl ing.None
      >
      >XMLReader.Read ()
      >XMLReader.Read ()
      >MsgBox(XMLRead er.GetAttribute ("Type"))
      >
      >XMLReader.Read ()
      >MsgBox(XMLRead er.GetAttribute ("Path"))
      >
      >XMLReader.Read ()
      >
      >While Not XMLReader.EOF *****Why isn't this looping?
      >
      XMLReader.Read( )
      >
      If Not XMLReader.IsSta rtElement() Then
      Exit While
      End If
      >
      MsgBox(XMLReade r.ReadElementSt ring("FilePath" ))
      >
      >End While
      >
      >XMLReader.Clos e()
      >
      >
      >
      >Any help would be greatly appreciated!
      >
      >

      Comment

      • Justin

        #4
        Re: New to XML. Need help reading XML.

        Perfect! Thanks for the info. After reading about 20 pages including MS I
        couldn't figure out how to loop at the end.

        This worked like a charm!


        "Martin Honnen" <mahotrash@yaho o.dewrote in message
        news:egvORZx7IH A.2544@TK2MSFTN GP04.phx.gbl...
        Justin wrote:
        >Here's my XML:
        >>
        ><?xml version="1.0" ?>
        ><AppMode Type="Network">
        ><CurrentFold er Path="c:\tabs">
        ><Tabs>
        ><FilePath>tabs \Justin.tab</FilePath>
        ><FilePath>tabs \Julie.tab</FilePath>
        >*****There could be 1 of these or 100....quantity can change*****
        ></Tabs>
        ></CurrentFolder>
        ></AppMode>
        >>
        >>
        >All I need to do is load "Network" and "c:\tabs" into variables. Then
        >each FilePath goes into an array.
        >
        One way is to use XPath to find the nodes:
        >
        Dim doc As New XPathDocument(" ..\..\XMLFile1. xml")
        Dim nav As XPathNavigator =
        doc.CreateNavig ator().SelectSi ngleNode("AppMo de")
        Dim type As String = nav.GetAttribut e("Type", "")
        Console.WriteLi ne("Type: {0}", type)
        nav = nav.SelectSingl eNode("CurrentF older")
        Dim path As String = nav.GetAttribut e("Path", "")
        Console.WriteLi ne("Path: {0}", path)
        Dim filePaths As XPathNodeIterat or = nav.Select("Tab s/FilePath")
        Console.WriteLi ne("Found {0} file path(s):", filePaths.Count )
        Dim paths(filePaths .Count) As String
        Dim i As Integer = 0
        For Each filePath As XPathNavigator In filePaths
        paths(i) = filePath.Value
        Console.WriteLi ne(paths(i))
        i = i + 1
        Next
        >
        >
        --
        >
        Martin Honnen --- MVP XML
        http://JavaScript.FAQTs.com/

        Comment

        • Justin

          #5
          Re: New to XML. Need help reading XML.

          Thanks for the info Steven. I had already implemented Martins approach.
          However I have more XML reading coming up so this is sure to come into play.

          Thanks for your time!



          "Steven Cheng [MSFT]" <stcheng@online .microsoft.comw rote in message
          news:bOzxONG8IH A.1620@TK2MSFTN GHUB02.phx.gbl. ..
          Hi Justin,
          >
          From your description, you want to extract some certain values from an XML
          document. In .net framework, there is quite rich API support for XML query
          and processing. Here you have three different possible means to do it:
          >
          1. Use the xmlreader as you've tried, this is a memory efficient approahc,
          but maybe more difficult to code(when xml is complex)
          >
          2. use XmlDocument + Xpath query, this is quite simple code
          >
          3. If you can use .NET 3.5, then "Linq to XML" is quite a good weapon you
          can utilize
          >
          Here I've produced sample code (extracting the elements you want) for all
          of the 3 approaches mentioned above:
          >
          ===========usin g XML Reader========= =======
          private void btnReader_Click (object sender, EventArgs e)
          {
          StreamReader sr = new StreamReader(@" ..\..\test.xml" ,
          Encoding.UTF8);
          XmlReader xr = XmlReader.Creat e(sr);
          >
          List<stringpath s = new List<string>();
          >
          while (xr.Read())
          {
          if (xr.IsStartElem ent("AppMode"))
          {
          MessageBox.Show (xr.GetAttribut e("Type"));
          }else if(xr.IsStartEl ement("CurrentF older"))
          {
          MessageBox.Show (xr.GetAttribut e("Path"));
          }
          else if (xr.IsStartElem ent("FilePath") )
          {
          paths.Add(xr.Ge tAttribute("Pat h"));
          }
          }
          >
          MessageBox.Show ("paths count: " + paths.Count);
          sr.Close();
          }
          =============== ======
          >
          ========USE XML document + xpath query========== ====
          private void btnXmlDoc_Click (object sender, EventArgs e)
          {
          XmlDocument doc = new XmlDocument();
          doc.Load(@"..\. .\test.xml");
          >
          string type =
          doc.SelectSingl eNode("/AppMode").Attri butes["Type"].Value;
          string curfolder =
          doc.SelectSingl eNode("/AppMode/CurrentFolder") .Attributes["Path"].Value;
          >
          XmlNodeList files = doc.SelectNodes ("//FilePath");
          >
          List<stringpath s = new List<string>();
          >
          foreach (XmlNode pnode in files)
          {
          paths.Add(pnode .InnerText);
          }
          >
          MessageBox.Show ("type: " + type + "\r\n"
          + "current folder: " + curfolder + "\r\n"
          + "paths count: " + paths.Count);
          >
          >
          }
          =============== ===============
          >
          >
          >
          ============ use LINQ TO XML =============== ====
          private void btnLinq_Click(o bject sender, EventArgs e)
          {
          StreamReader sr = new StreamReader(@" ..\..\test.xml" ,
          Encoding.UTF8);
          XDocument xdoc = XDocument.Load( sr);
          sr.Close();
          >
          >
          string type = xdoc.Element("A ppMode").Attrib ute("Type").Val ue;
          var cfs = from cf in xdoc.Descendant s("CurrentFolde r")
          select cf.Attribute("P ath").Value;
          >
          string curfolder = cfs.First();
          >
          var paths = from fp in xdoc.Descendant s("FilePath")
          select fp.Value;
          >
          List<stringfpat hs = paths.ToList();
          >
          MessageBox.Show ("type: " + type + "\r\n"
          + "current folder: " + curfolder + "\r\n"
          + "paths count: " + fpaths.Count);
          >
          }
          =============== ==============
          >
          if you want to know more about LINQ to XML, please have a look at the MSDN
          reference:
          >
          #.NET Language-Integrated Query for XML Data

          >
          Sincerely,
          >
          Steven Cheng
          >
          Microsoft MSDN Online Support Lead
          >
          >
          Delighting our customers is our #1 priority. We welcome your comments and
          suggestions about how we can improve the support we provide to you. Please
          feel free to let my manager know what you think of the level of service
          provided. You can send feedback directly to my manager at:
          msdnmg@microsof t.com.
          >
          =============== =============== =============== =====
          Get notification to my posts through email? Please refer to
          Gain technical skills through documentation and training, earn certifications and connect with the community

          ications.
          >
          Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
          where an initial response from the community or a Microsoft Support
          Engineer within 1 business day is acceptable. Please note that each follow
          up response may take approximately 2 business days as the support
          professional working with you may need further investigation to reach the
          most efficient resolution. The offering is not appropriate for situations
          that require urgent, real-time or phone-based interactions or complex
          project analysis and dump analysis issues. Issues of this nature are best
          handled working with a dedicated Microsoft Support Engineer by contacting
          Microsoft Customer Support Services (CSS) at
          http://msdn.microsoft.com/subscripti...t/default.aspx.
          =============== =============== =============== =====
          This posting is provided "AS IS" with no warranties, and confers no
          rights.
          --------------------
          >>From: "Justin" <None@None.co m>
          >>Subject: New to XML. Need help reading XML.
          >>Date: Sat, 26 Jul 2008 00:24:30 -0700
          >
          >>
          >>Here's my XML:
          >>
          >><?xml version="1.0" ?>
          >><AppMode Type="Network">
          >><CurrentFolde r Path="c:\tabs">
          >><Tabs>
          >><FilePath>tab s\Justin.tab</FilePath>
          >><FilePath>tab s\Julie.tab</FilePath>
          >>*****There could be 1 of these or 100....quantity can change*****
          >></Tabs>
          >></CurrentFolder>
          >></AppMode>
          >>
          >>
          >>All I need to do is load "Network" and "c:\tabs" into variables. Then
          each
          >>FilePath goes into an array.
          >>
          >>The following code gives me everything but Julie.tab. It only gives me
          one
          >>of the FilePaths. I'm not even sure if this is the right/best way to do
          >>this:
          >>
          >>Dim XMLReader As XmlTextReader = New XmlTextReader(" ")
          >>XMLReader.Whi tespaceHandling = WhitespaceHandl ing.None
          >>
          >>XMLReader.Rea d()
          >>XMLReader.Rea d()
          >>MsgBox(XMLRea der.GetAttribut e("Type"))
          >>
          >>XMLReader.Rea d()
          >>MsgBox(XMLRea der.GetAttribut e("Path"))
          >>
          >>XMLReader.Rea d()
          >>
          >>While Not XMLReader.EOF *****Why isn't this looping?
          >>
          > XMLReader.Read( )
          >>
          > If Not XMLReader.IsSta rtElement() Then
          > Exit While
          > End If
          >>
          > MsgBox(XMLReade r.ReadElementSt ring("FilePath" ))
          >>
          >>End While
          >>
          >>XMLReader.Clo se()
          >>
          >>
          >>
          >>Any help would be greatly appreciated!
          >>
          >>
          >

          Comment

          • Steven Cheng [MSFT]

            #6
            Re: New to XML. Need help reading XML.

            Thanks for your reply Justin,

            No problem. If you need any help on this later, please feel free to post
            here.

            Sincerely,

            Steven Cheng

            Microsoft MSDN Online Support Lead


            Delighting our customers is our #1 priority. We welcome your comments and
            suggestions about how we can improve the support we provide to you. Please
            feel free to let my manager know what you think of the level of service
            provided. You can send feedback directly to my manager at:
            msdnmg@microsof t.com.

            =============== =============== =============== =====
            Get notification to my posts through email? Please refer to
            Gain technical skills through documentation and training, earn certifications and connect with the community

            ications.
            =============== =============== =============== =====
            This posting is provided "AS IS" with no warranties, and confers no rights.

            --------------------
            >From: "Justin" <None@None.co m>
            >References: <#J3ZYCv7IHA.36 52@TK2MSFTNGP04 .phx.gbl>
            <bOzxONG8IHA.16 20@TK2MSFTNGHUB 02.phx.gbl>
            >Subject: Re: New to XML. Need help reading XML.
            >Date: Mon, 28 Jul 2008 21:50:27 -0700
            >Thanks for the info Steven. I had already implemented Martins approach.
            >However I have more XML reading coming up so this is sure to come into
            play.
            >
            >Thanks for your time!
            >
            >
            >
            >"Steven Cheng [MSFT]" <stcheng@online .microsoft.comw rote in message
            >news:bOzxONG8I HA.1620@TK2MSFT NGHUB02.phx.gbl ...
            >Hi Justin,
            >>
            >From your description, you want to extract some certain values from an
            XML
            >document. In .net framework, there is quite rich API support for XML
            query
            >and processing. Here you have three different possible means to do it:
            >>
            >1. Use the xmlreader as you've tried, this is a memory efficient
            approahc,
            >but maybe more difficult to code(when xml is complex)
            >>
            >2. use XmlDocument + Xpath query, this is quite simple code
            >>
            >3. If you can use .NET 3.5, then "Linq to XML" is quite a good weapon you
            >can utilize
            >>
            >Here I've produced sample code (extracting the elements you want) for all
            >of the 3 approaches mentioned above:
            >>
            >===========usi ng XML Reader========= =======
            > private void btnReader_Click (object sender, EventArgs e)
            > {
            > StreamReader sr = new StreamReader(@" ..\..\test.xml" ,
            >Encoding.UTF8) ;
            > XmlReader xr = XmlReader.Creat e(sr);
            >>
            > List<stringpath s = new List<string>();
            >>
            > while (xr.Read())
            > {
            > if (xr.IsStartElem ent("AppMode"))
            > {
            > MessageBox.Show (xr.GetAttribut e("Type"));
            > }else if(xr.IsStartEl ement("CurrentF older"))
            > {
            > MessageBox.Show (xr.GetAttribut e("Path"));
            > }
            > else if (xr.IsStartElem ent("FilePath") )
            > {
            > paths.Add(xr.Ge tAttribute("Pat h"));
            > }
            > }
            >>
            > MessageBox.Show ("paths count: " + paths.Count);
            > sr.Close();
            > }
            >============== =======
            >>
            >========USE XML document + xpath query========== ====
            >private void btnXmlDoc_Click (object sender, EventArgs e)
            > {
            > XmlDocument doc = new XmlDocument();
            > doc.Load(@"..\. .\test.xml");
            >>
            > string type =
            >doc.SelectSing leNode("/AppMode").Attri butes["Type"].Value;
            > string curfolder =
            >doc.SelectSing leNode("/AppMode/CurrentFolder") .Attributes["Path"].Value;
            >>
            > XmlNodeList files = doc.SelectNodes ("//FilePath");
            >>
            > List<stringpath s = new List<string>();
            >>
            > foreach (XmlNode pnode in files)
            > {
            > paths.Add(pnode .InnerText);
            > }
            >>
            > MessageBox.Show ("type: " + type + "\r\n"
            > + "current folder: " + curfolder + "\r\n"
            > + "paths count: " + paths.Count);
            >>
            >>
            > }
            >============== =============== =
            >>

            Comment

            Working...