Solved

how to read data from xml

Posted on 2013-06-18
12
319 Views
Last Modified: 2013-06-21
hi experts, i have this xml below:

<response type="categories_listing" generation_date_gmt="Tue, 18 Jun 2013 10:26:28 GMT">
<url>
http://localhost/sml.xml
</url>
<categories site="test">
<category id="1368" adult="N" name="Arte e Artesanato">
<category id="5460" adult="N" name="Artesanato"></category>
<category id="2662" adult="N" name="Esculturas"></category>
<category id="40285" adult="N" name="Ferramentas e Materiais"></category>
<category id="1370" adult="N" name="Gravuras"></category>
<category id="5464" adult="N" name="Livros"></category>
<category id="1369" adult="N" name="Pinturas"></category>
<category id="1371" adult="N" name="Outros"></category>
</category>
<category id="1051" adult="N" name="Celulares e Telefones">
<category id="3813" adult="N" name="Acessórios para Celulares"></category>
<category id="7475" adult="N" name="Cartões de Memória"></category>
<category id="1055" adult="N" name="Celulares"></category>
<category id="5427" adult="N" name="Nextel"></category>
<category id="1058" adult="N" name="Rádio Amador"></category>
<category id="46195" adult="N" name="Telefones"></category>
<category id="7502" adult="N" name="VoIP"></category>
<category id="2908" adult="N" name="Walkie - Talkies"></category>
<category id="1915" adult="N" name="Outros"></category>
</category>
</response>

Open in new window


now, i can't change the xml, so i want to populate an listview with the category and subcategory. how can i do that
0
Comment
Question by:rafaelrgl
  • 5
  • 5
  • 2
12 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 39256086
where's the subcategory?
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 39256115
well, this


<category id="1368" adult="N" name="Arte e Artesanato">
      <category id="5460" adult="N" name="Artesanato"></category>
      <category id="2662" adult="N" name="Esculturas"></category>
      <category id="40285" adult="N" name="Ferramentas e Materiais"></category>
      <category id="1370" adult="N" name="Gravuras"></category>
     <category id="5464" adult="N" name="Livros"></category>
     <category id="1369" adult="N" name="Pinturas"></category>
     <category id="1371" adult="N" name="Outros"></category>
</category>

i formated above so you can see there is category id="1368" and the others inside are subcategorys.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 39256275
since xml contains hierarchy using tree-view control is better approach.
how would u like to display this kind of structure in listview?
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39256301
Hi rafaelrgl;

The following code uses Linq to XML to query the document and build your ListView control.

using System.Xml.Linq;

// Load the XML file from the file system. Change path to the file below
XDocument doc = XDocument.Load("C:/Working Directory/Response.xml");

// Get a reference to the categories node
XElement categoriesElements = doc.Root.Element("categories");

// Query the document for the needed info.
var results = (from d in categoriesElements.Elements("category")
               select new
                          {
                              Parent = d.Attribute("name").Value,
                              Children = (from c in d.Elements("category")
                                          select c.Attribute("name").Value).ToList()
                          }).ToList();

// Build your list view items
foreach (var node in results)
{
    // New parent node
    var lItem = new ListViewItem(node.Parent);
    foreach (var child in node.Children)
    {
        // Add all children nodes
        lItem.SubItems.Add(child);
    }
    // Attach parent node to the list view control
    listView1.Items.Add(lItem);
}

Open in new window

0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 39256320
i mean tree-view, sorry  sedgwick. how this can be accomplish
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 39256324
@FernandoSoto
what did u set to the View property of the listview?
there's no correlation between the parent categories and the child categories when u display them in listview in this matter.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 42

Expert Comment

by:sedgwick
ID: 39256335
here in treeview:
        private void populateTreeview()
        {
            WebRequest req = WebRequest.Create("http://www.mercadolivre.com.br/jm/categsXml?as_site_id=MLB&as_max_level=2");
            WebResponse resp = req.GetResponse();
            StreamReader textReader = new StreamReader(resp.GetResponseStream());
            XmlTextReader xmlReader = new XmlTextReader(textReader);

            xmlReader.XmlResolver = null;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = null;
            xmlDoc.Load(xmlReader);
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name));
            TreeNode tNode = new TreeNode();
            tNode = (TreeNode)treeView1.Nodes[0];
            addTreeNode(xmlDoc.DocumentElement, tNode);
            treeView1.ExpandAll();

        }
        //This function is called recursively until all nodes are loaded
        private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList xNodeList;
            if (xmlNode.HasChildNodes) //The current node has children
            {
                xNodeList = xmlNode.ChildNodes;
                for (int x = 0; x <= xNodeList.Count - 1; x++)
                //Loop through the child nodes
                {
                    xNode = xmlNode.ChildNodes[x];
                    treeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = treeNode.Nodes[x];
                    addTreeNode(xNode, tNode);
                }
            }
            else //No children, so add the outer xml (trimming off whitespace)
                treeNode.Text = xmlNode.OuterXml.Trim();
        }

Open in new window

0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 39256377
sedgwick, did this code worked for you, did you tested, because for me did not worked. i does not show the content right.

Imports System.Net
Imports System.Xml
Imports System.IO

Partial Class WebUserControl_CategoriasVertical
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        populateTreeview()

    End Sub
    Private Sub populateTreeview()
        Dim req As WebRequest = WebRequest.Create("http://www.mercadolivre.com.br/jm/categsXml?as_site_id=MLB&as_max_level=2")
        Dim resp As WebResponse = req.GetResponse()
        Dim textReader As New StreamReader(resp.GetResponseStream())
        Dim xmlReader As New XmlTextReader(textReader)

        xmlReader.XmlResolver = Nothing
        Dim xmlDoc As New XmlDocument()
        xmlDoc.XmlResolver = Nothing
        xmlDoc.Load(xmlReader)
        TreeView1.Nodes.Clear()
        TreeView1.Nodes.Add(New TreeNode(xmlDoc.DocumentElement.Name))
        Dim tNode As New TreeNode()
        tNode = DirectCast(TreeView1.Nodes(0), TreeNode)
        addTreeNode(xmlDoc.DocumentElement, tNode)
        TreeView1.ExpandAll()

    End Sub
    'This function is called recursively until all nodes are loaded
    Private Sub addTreeNode(xmlNode As XmlNode, treeNode As TreeNode)
        Dim xNode As XmlNode
        Dim tNode As TreeNode
        Dim xNodeList As XmlNodeList
        If xmlNode.HasChildNodes Then
            'The current node has children
            xNodeList = xmlNode.ChildNodes
            For x As Integer = 0 To xNodeList.Count - 1
                'Loop through the child nodes
                xNode = xmlNode.ChildNodes(x)
                treeNode.ChildNodes.Add(New TreeNode(xNode.Name))
                tNode = treeNode.ChildNodes(x)
                addTreeNode(xNode, tNode)
            Next
        Else
            'No children, so add the outer xml (trimming off whitespace)
            treeNode.Text = xmlNode.OuterXml.Trim()
        End If
    End Sub

Open in new window

0
 
LVL 42

Accepted Solution

by:
sedgwick earned 250 total points
ID: 39256402
it worked perfectly:screenshot
0
 
LVL 62

Assisted Solution

by:Fernando Soto
Fernando Soto earned 250 total points
ID: 39256417
Hi rafaelrgl;

The following code uses Linq to XML to query the document and build your TreeView control.
The only difference between this solution and the last is the foreach loop.

using System.Xml.Linq;

// Load the XML file from the file system. Change path to the file below
XDocument doc = XDocument.Load("C:/Working Directory/Response.xml");

// Get a reference to the categories node
XElement categoriesElements = doc.Root.Element("categories");

// Query the document for the needed info.
var results = (from d in categoriesElements.Elements("category")
               select new
                          {
                              Parent = d.Attribute("name").Value,
                              Children = (from c in d.Elements("category")
                                          select c.Attribute("name").Value).ToList()
                          }).ToList();

// Build your TreeView Nodes
foreach (var node in results)
{
    // New TreeView Node
    var tvNode = new TreeNode(node.Parent);
    foreach (var child in node.Children)
    {
        // Add all children nodes
        tvNode.Nodes.Add(new TreeNode(child));
    }
    // Attach parent node to the TreeView control
    treeView1.Nodes.Add(tvNode);
}

Open in new window

0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 39256421
i see, you are using the win32 version, i want for asp.net webforms, and i don't want to show the xml file, but the category like this:


Arte e Artesanato
         Artesanato
         Esculturas
         Ferramentas e Materiais
         Gravuras


and i want to be able to have this as an link, so i can build some propertys like put the id on the link, so on.
0
 
LVL 1

Author Comment

by:rafaelrgl
ID: 39256475
hi fernando, i am not use to Linq.

So how do i make this sample to work on asp.net using vb.net
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How to open a link from vb.net app 3 9
ConsoleSql 1 18
Copy/Clone an object. 9 17
Get list of word ducuments in a folder 10 18
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now