Solved

loading Selected nodes of XML in a dataset

Posted on 2006-07-18
18
368 Views
Last Modified: 2012-08-14
I have an XML file like this

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <cart>
    <userID>bob</userID>
    <ProductID>2</ProductID>
    <ProductName>Book</ProductName>
    <UnitPrice>185.00</UnitPrice>
    <Quantity>1</Quantity>
  </cart>
  <cart>
    <userID>bob</userID>
    <ProductID>8</ProductID>
    <ProductName>Pen</ProductName>
    <UnitPrice>300.00</UnitPrice>
    <Quantity>1</Quantity>
  </cart>
  <cart>
    <userID>tim</userID>
    <ProductID>8</ProductID>
    <ProductName>Pen</ProductName>
    <UnitPrice>300.00</UnitPrice>
    <Quantity>1</Quantity>
  </cart>
</NewDataSet>


I want to retrieve only those cart elements from xml file matching the userID=bob  and populate Dataset with this Particular information.
In this case I want dataset to have only two datarows only.

Is there anyway I can acheive this.
Thanks.
0
Comment
Question by:skvikram
  • 10
  • 8
18 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17139960
Load the DataSet with DataSet.ReadXML, and then filter by userID = 'bob'.

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17140558
that is possible. what I want is only selected nodes in DATASET not the entire XML file.

I want to populate by using something like this type of statement
select * from [table1] where [condition1]
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17140607
If that is true, then you will have use something like an XmlTextReader or an XmlDocument with XPath expression go get the data and append rows to a DataTable.

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17143541
yes TheLearnedone, I know xpathnavigator and xpathnodeiterator will do,
the job the question is HOW??
Can u supply me some code specific to my problem where UserID is a GUID value in XML file
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17151030
If you want code, do you want VB.NET or C#?  This is the generic .NET topic area, so I can't tell. BTW, there are more specific VB.NET and C# areas that would be more appropriate for this question, since you need code.

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17151887
VB.NET or C# anything will do. I am not language dependent.
since it is generic .NET topic area that's why I asked it here to get maximum responses in any .NET language. but still I am getting response from you only.
0
 
LVL 7

Author Comment

by:skvikram
ID: 17151893
please keep in mind UserID is a GUID value in XML file
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17160384
Do you have .NET 2005, 2003 or 2002?

Bob
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 250 total points
ID: 17160449
Try this:

Imports System.Xml

...

    BuildDataTableFromXml("c:\temp\test.", "userID", "bob")
 
...

  Public Function BuildDataTableFromXml(ByVal rootPath As String, ByVal filterColumn As String, ByVal filterCondition As String) As DataTable

    Dim xsdFileName As String = rootPath & "xsd"
    Dim xmlFileName As String = rootPath & "xml"

    Dim table As DataTable

    Try

      ' Build an XmlDataDocument that is optimized for DataSet operations
      Dim doc As New XmlDataDocument
      doc.DataSet.ReadXmlSchema(xsdFileName)
      doc.Load(xmlFileName)

      ' Clone the structure of the table to add certain records to.
      table = doc.DataSet.Tables(0).Clone

      ' Go through all the record nodes, looking for any condition, and
      ' adding them to the returned DataTable.
      For Each node As XmlElement In doc.SelectNodes("//cart")

        ' Build a DataRow from the 'cart' element.
        Dim row As DataRow = doc.GetRowFromElement(node)

        ' Add a row to DataTable, if the filter condition is not valid or
        ' if the filter condition is met.
        Dim willAddRow As Boolean = (filterColumn.Length = 0 Or filterCondition.Length = 0) OrElse row(filterColumn).ToString() = filterCondition

        If willAddRow Then
          table.ImportRow(row)
        End If
      Next

    Catch ex As Exception
      MessageBox.Show(ex.ToString)
    End Try

    Return table

  End Function

Bob
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 96

Expert Comment

by:Bob Learned
ID: 17160460
C#:

using System;
using System.Data;
using System.Xml;

public class DataSetBuilder
{

  public static DataTable BuildDataTableFromXml(string rootPath, string filterColumn, string filterCondition)
  {
    string xsdFileName = rootPath + "xsd";
    string xmlFileName = rootPath + "xml";
    DataTable table;
    XmlDataDocument doc = new XmlDataDocument();
    doc.DataSet.ReadXmlSchema(xsdFileName);
    doc.Load(xmlFileName);
    table = doc.DataSet.Tables[0].Clone();
    foreach (XmlElement node in doc.SelectNodes("//cart"))
    {
      DataRow row = doc.GetRowFromElement(node);
      bool willAddRow = (filterColumn.Length == 0 | filterCondition.Length == 0) || row[filterColumn].ToString() == filterCondition;
      if (willAddRow)
      {
        table.ImportRow(row);
      }
    }
    return table;
  }
}

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17160963
I wanted to load the xml file in a dataset which has other datatables also.
I don't know how to convert the datatable obtained from your code into a dataset. And utilize it in my existing code.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17161702
Public Function BuildDataFromXml(ByVal rootPath As String, ByVal filterColumn As String, ByVal filterCondition As String) As DataSet

Dim ds As New DataSet

...
' Do the other code here

ds.Tables.Add(table)

Return ds

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17175576
thanks,
But How can I add new entries in XML file when I get the contents of XML file in a dataset through datatable.
Is it possible
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17175706
If you load the DataSet with DataSet.ReadXml, it would be trivial.  But, if you are handling the XML parsing, it would be much more difficult.

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17248340
>>>>If you load the DataSet with DataSet.ReadXml, it would be trivial.  But, if you are handling the XML parsing, it would be much more difficult.<<<<

So how to accomplish the job of adding new entries in XML file when I get the contents of XML file in a dataset through datatable.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17254178
Are you asking how to add rows to a DataSet that is loaded my way or the DataSet.ReadXML way?

If you are talking about my code, then table.Rows.Add(row) is all you need.

Bob
0
 
LVL 7

Author Comment

by:skvikram
ID: 17256907
i am asking about ur way of rows addition.

can u please explain by a little example.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17258946
Since you get a DataTable from BuildDataTableFromXml, this is how you would add a row:

DataRow row = table.NewRow();
row["Field"] = "Value";
table.Rows.Add(row);

Bob
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

705 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