Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using ASP.NET for altering XML

Status
Not open for further replies.

toddw607

Programmer
Apr 2, 2007
55
US
I'm trying to divide up groups in a XML file by group and place them into SQL Server with each group being in a separate row of a SQL Server table. What I mean by group is that each dataset begins and ends with the same tag and including all the information inside that group. My main problem with this is the actual dividing up of the groups. Does anyone know a good tutorial to get me on my way. Thanks.
 
if you post some sample data and a desired output we may be able to help.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Here is a small example of my xml file:

<SectionHeadingbegin wp:type="para"
wp:id="1002379"
wp:style="display: block; color: #000000; font-style: normal; font-weight: bold; margin-bottom: 14pt; margin-left: 0pt; margin-right: 0pt; margin-top: 0pt; text-align: justify; text-decoration: none; text-indent: 0pt; text-transform: uppercase; vertical-align: baseline">
10-1. Introduction
</SectionHeadingbegin>
<PrimarySidehead wp:type="para"
wp:id="1011443"
wp:style="display: block; color: #000000; font-style: normal; font-weight: bold; margin-bottom: 7pt; margin-left: 54pt; margin-right: 0pt; margin-top: 14pt; text-align: left; text-decoration: none; text-indent: -54pt; text-transform: none; vertical-align: baseline">
10-1.1. General.
</PrimarySidehead>
<Body wp:type="para"
wp:class="Body"
wp:id="1011447"
wp:style="display: block;">
This chapter contains descriptions, procedures, and troubleshooting information for Lighting. This chapter is used to:
</Body>
<BodyBullets wp:type="para"
wp:id="1011452"
wp:style="display: block; color: #000000; font-style: normal; font-weight: normal; margin-bottom: 0pt; margin-left: 36pt; margin-right: 0pt; margin-top: 0pt; text-align: justify; text-decoration: none; text-indent: -18pt; text-transform: none; vertical-align: baseline">
• Gain an understanding of lighting,
</BodyBullets>
<BodyBullets wp:type="para"
wp:id="1011456"
wp:style="display: block; color: #000000; font-style: normal; font-weight: normal; margin-bottom: 0pt; margin-left: 36pt; margin-right: 0pt; margin-top: 0pt; text-align: justify; text-decoration: none; text-indent: -18pt; text-transform: none; vertical-align: baseline">
• Determine the cause of on-car lighting malfunctions,
</BodyBullets>
<BodyBullets wp:type="para"
wp:id="1011457"
wp:style="display: block; color: #000000; font-style: normal; font-weight: normal; margin-bottom: 0pt; margin-left: 36pt; margin-right: 0pt; margin-top: 0pt; text-align: justify; text-decoration: none; text-indent: -18pt; text-transform: none; vertical-align: baseline">
• Perform on-car corrective and preventive maintenance.
</BodyBullets>
<PrimarySidehead wp:type="para"
wp:id="1011458"
wp:style="display: block; color: #000000; font-style: normal; font-weight: bold; margin-bottom: 7pt; margin-left: 54pt; margin-right: 0pt; margin-top: 14pt; text-align: left; text-decoration: none; text-indent: -54pt; text-transform: none; vertical-align: baseline">
10-1.2. Safety.
</PrimarySidehead>
<Body wp:type="para"
wp:class="Body"
wp:id="1011462"
wp:style="display: block;">
Refer to the warning page at the beginning of this manual, for a listing of all general safety precautions and Paragraph <wp:GotoLink wp:href="PWM1001TEST.xml#1011464">10-1.3</wp:GotoLink> for an explanation of all warnings, cautions, and notes. The warning page and Paragraph <wp:GotoLink wp:href="PWM1001TEST.xml#1011464">10-1.3</wp:GotoLink> must be read, understood, and adhered to before operating or working on the cars or their equipment. Also, individual procedures in this chapter contain specific warnings, cautions, and notes.
</Body>
<Body wp:type="para"
wp:class="Body"
wp:id="1011463"
wp:style="display: block;">
All personnel must be thoroughly familiar with maintenance instructions and all pertinent warnings, cautions, and notes prior to operating or maintaining the car. Failure to follow procedures and warnings, cautions and notes can cause loss of life or serious injury to personnel and/or malfunction or damage to equipment.
</Body>
<PrimarySidehead wp:type="para"
wp:id="1011464"
wp:style="display: block; color: #000000; font-style: normal; font-weight: bold; margin-bottom: 7pt; margin-left: 54pt; margin-right: 0pt; margin-top: 14pt; text-align: left; text-decoration: none; text-indent: -54pt; text-transform: none; vertical-align: baseline">
10-1.3. Warnings, Cautions, and Notes
</PrimarySidehead>
<Body wp:type="para"
wp:class="Body"
wp:id="1011465"
wp:style="display: block;">
The Warnings, Cautions, and Notes in this publication highlight areas of concern to maintenance personnel. The definitions of warnings, cautions, and notes as utilized throughout this publication are as follows:
</Body>
<Warningpagewarning wp:type="para"
wp:id="1011469"
wp:style="display: block; color: #000000; font-style: normal; font-weight: normal; margin-bottom: 0pt; margin-left: 0pt; margin-right: 0pt; margin-top: 7pt; text-align: justify; text-decoration: none; text-indent: 0pt; text-transform: none; vertical-align: baseline">
Indicates an operation, sequence, or function which, if not observed, may cause loss of life or serious injury to personnel and/or may cause a critically unsafe conditions of the car. Strictly adhere to all Warnings.
</Warningpagewarning>
<WarningpageCaution wp:type="para"
wp:id="1011476"
wp:style="display: block; color: #000000; font-style: normal; font-weight: normal; margin-bottom: 0pt; margin-left: 0pt; margin-right: 0pt; margin-top: 7pt; text-align: justify; text-decoration: none; text-indent: 0pt; text-transform: none; vertical-align: baseline">
Indicates an operation, sequence, or function which, if not observed, may cause damage to or malfunction of equipment and/or may cause a non-critical malfunction on the car. Strictly adhere to all Cautions.
</WarningpageCaution>
<WarningpageNote wp:type="para"
wp:id="1011471"
wp:style="display: block; color: #000000; font-style: normal; font-weight: normal; margin-bottom: 0pt; margin-left: 0pt; margin-right: 0pt; margin-top: 7pt; text-align: justify; text-decoration: none; text-indent: 0pt; text-transform: none; vertical-align: baseline">
Provides explanatory information / clarification not readily apparent in the text or illustrations of a procedure.
</WarningpageNote>
<SectionHeading wp:type="para"
wp:id="999109"
wp:style="display: block; color: #000000; font-style: normal; font-weight: bold; margin-bottom: 14pt; margin-left: 36pt; margin-right: 0pt; margin-top: 14pt; text-align: left; text-decoration: none; text-indent: -36pt; text-transform: uppercase; vertical-align: baseline">
10-2. Operation and Functional System Description
</SectionHeading>
<PrimarySidehead wp:type="para"
wp:id="1011530"
wp:style="display: block; color: #000000; font-style: normal; font-weight: bold; margin-bottom: 7pt; margin-left: 54pt; margin-right: 0pt; margin-top: 14pt; text-align: left; text-decoration: none; text-indent: -54pt; text-transform: none; vertical-align: baseline">
10-2.1. General Information
</PrimarySidehead>


I wanted all of the <PrimarySideHead> tags to be separated and all the information inside them to be placed in their own respective rows in a table with each row being referenced by the wp:id. I am trying to get the SQL Server table to have 2 columns. In the left column would be just the wp:id and all the rest of the text in the right column. Do you know anywhere I could learn how to do this, or any ideas where to start. Getting started is always the hard part for me. Thanks
 
sudo code
Code:
XmlDocument doc = new XmlDocument();
doc.Load(@"[file name]");
[COLOR=green]//doc.LoadXml([string variable]); // if it's a string and not a file[/color]

ListDictionary data = new ListDictionary()
string id, style;
foreach(XmlNode node in doc.SelectNodes("//PrimarySidehead"))
{
   id = node.Attributes["id"].Value;
   style = node.Attributes["style"].Value;
   data.add(id, style);
}

SqlConnection cnn = new SqlConnection([connection string]);
SqlCommand cmd = new SqlCommand("insert into my table (@id, @style)", cnn);

cnn.Open();
foreach(DictionaryEntry entry in data)
{
   cmd.Parameters["id"].Value = entry.key;
   cmd.Parameters["style"].Value = entry.Value;
   cmd.ExecuteNonQuery();
}
cnn.Close();

cnn.Dispose();
doc.Dispose();
there is also the SqlBulkCopy object which would probally work better in this situation (requires datatable instead of hashtable). but this gives the basics of database objects (connection, command, parameters).

for more information search ado.net for database connectivity. There are many 3rd party tools for accessing databases.
MS Enterprise Library has a data access block.
There is Castle's ActiveRecord, Solution Design's LLBL OR Mapper, nHibernate project.

search DAL, Data Acces Model, OR Mapper for more 3rd party tools. EntLib and nHibernate are open source. LLBL is a commercial product.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Thanks for the RE:, lots of good info. My problem is that I need to place multiple xml documents into SQL Server and then have them returned in ASP.NET. I have all the details (connection strings, params, etc) figured out but I'm not sure what system.xml class to use. Also, do you know a good way I could place a XSL file in the same table and have the xml document able to reference the xsl file in ASP.NET when the xsl file is still located in the SQL Server table? Thanks again.
 
so you want to store segments of xml in the DB, not the individual values of a attributes and inner text. then have the db read out the segments and display on screen. (SXLT to follow as well). correct?

ok, similiar to before execpt instead of reading out the attributes and inner text into variables, read the [tt]node.OutterXml[/tt] into a string. save this string to a varchar field in a table. (same would be true for XSLT)

when you need to display it read the data from the database (via DAL or datareader) and place the contents of the XML field into a string variable. (same with XSLT)

the use the XSLTCompiledTransform object (System.XML.XSLT namespace) to format the xml string variable.

you may need to pass the xml/xslt string variables to an XmlWriter/Reader before the XSLTCompiledTransform object.

for more information check out System.XML and System.XML.XSLT namespace along with XmlDocument and
XSLTCompiledTransform for more information on minipulating XML

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi Jason,
ok, this is what I have so far:
Dim docXMLFile as New XMLDocument
docXMLFile.Load("myfileName.xml")
ListDictionary data = new ListDictionary
Dim myXML as String
For Each (XMLNode node in docXMLFile.SelectNodes("//PrimarySidehead))
{
id = node.OuterXML
}

SqlConnection cnn = new SqlConnection([connection String])
SqlCommand cmd = new SqlCommand("insert into myTable(@myXML)", cnn)

cnn.Open()

For Each (DictionaryEntry entry in data)
{
cmd.Parameters["id"].Value = entry.Value
cmd.ExecuteNonQuery()
}
cnn.Close()

Does this look correct? I did not add in the xslt transformation because it looks almost the same as the input for the xml file. A few things I do not understand are:
1.) After the xml document is split up and each section is placed in it's own row in the table then how do I reference the correct section? As of right now I have a n ASP.NET site map that calls a asp.net page that contains the following line of code:
<asp:xml id="xmlDisp" runat="server" documentsource="section1.xml">
</asp:xml>

This just brings up the xml document without the .xsl. Should I just make one application to split up the xml and upload it into an SQL Server table then construct a code to reference each section and copy/paste it into every asp.net page that calls that particular section of XML? I think that's my only question for right now. Thanks for taking a look.
 
toddw607 said:
After the xml document is split up and each section is placed in it's own row in the table then how do I reference the correct section?
you will need an identifier field within the [tt]MyTable[/tt] table. so the table structure would look like this
Code:
MyTable
--------
field1 int (Primary Key),
field2 varchar(1000)
store the xml in field2 and identifier in field1. Get the data like this
Code:
select field2 from MyTable where field1 = @field1
a SqlCommand.ExecuteScalar() will work better in this situtation.
what is the [tt]'id'[/tt] variable? you use it in the foreach loop, but never define it. also, by the time the loop ends [tt]'id'[/tt] will equal the outter xml of the last node. the loop should look like this. I also added a transaction so if anything goes wrong the whole operation rollsback.
Code:
For Each (XMLNode node in docXMLFile.SelectNodes("//PrimarySidehead))
{
   data.Add("[unique key]", node.OutterXml);
}
... create cnn
Dim transaction as SqlTransaction
Dim cmd as SqlCommand = new SqlCommand("insert into myTable(@field1, @field2)", cnn)
cmd.Parameters.Add("field1", SqlDBType.Int)
cmd.Parameters.Add("field2", SqlDBType.VarChar)
try
   cnn.Open();
   cmd.Transaction = cnn.BeginTransaction();
   For Each(DictionaryEntry entry in Data)
   {
      cmd.Parameters("field1") = entry.Key
      cmd.Parameters("field2") = entry.Value
      cmd.ExecuteNonQuery()
   }
   cmd.Transaction.Commit();
catch SqlException
   cmd.Transaction.Rollback();
   //report error
Finally
   cnn.Close()
   cnn.Dispose()
End Try
toddw607 said:
This just brings up the xml document without the .xsl. Should I just make one application to split up the xml and upload it into an SQL Server table then construct a code to reference each section and copy/paste it into every asp.net page that calls that particular section of XML? I think that's my only question for right now.
not sure exactly what you mean.
I wouldn't do any type of copy/paste. instead build a static class to get the data.
Code:
public static class MyClass
   public static function GetXML(int field1) as string
      //declare connection and command object
      dim string toReturn = string.Emtpy
      try
        toReturn = (string)cmd.ExecuteScalar()
      catch
      finally
        cnn.close()
        cnn.dispose()
      end try
      return toReturn
   end function
end class
then call from another object
Code:
string xml = MyClass.GetXML(1)
or build a base class which all your necessary webform inherit from
Code:
public class MyWebForm Inherits System.Web.UI.Page
    protected function GetXML(int field1) as string
      //declare connection and command object
      dim string toReturn = string.Emtpy
      try
        toReturn = (string)cmd.ExecuteScalar()
      catch
      finally
        cnn.close()
        cnn.dispose()
      end try
      return toReturn
   end function
end class
then each webform would use the class like this
Code:
public class WebFrom1 Inherits MyWebForm
    protected sub Page_Load(...)
       string xml = Me.GetXML(1)
    end sub
end class
either way you don't need to copy/paste the same code over and over.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi,
Thanks for the info, I'm still trying to learn ASP.NET. I thought I was getting the hang of it until now. I did what you said and I 'm getting the following error:
Compiler Error Message: ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl).

Source Error:

Line 1: Imports System
Line 2: Imports System.Data
Line 3: Imports System.Configuration

This error is coming from the following code:
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Public Class WebForm2
Inherits myWebForm
Dim xml As String
xml = New String(newClass.GetXML(100100))

End Class

I've also made another function that looks like this:

Public Class newClass
Inherits System.Web.UI.Page
Public Function GetXML(ByVal id As Integer) As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim toReturn As String
cnn = New SqlConnection("Data Source=SQLSERVER;Initial Catalog=upsizedCandidate;Integrated Security=SSPI")
cmd = New SqlCommand("Select xmltext FROM PATHfiles where id = @id ", cnn)

Try
toReturn = String.cmd.ExecuteScalar

Catch
Finally
cnn.Close()
cnn.Dispose()

End Try
Return toReturn
End Function
End Class

And both of these functions are being called from this aspx page:
<%@ Page Language="VB" MasterPageFile="~/SiteMapPages/SiteMap.master" CodeFile="WebForm2.aspx.vb" Inherits="newClass" Title="Server" %>
<asp:content id="Content2" contentplaceholderid="new" runat="Server">
<h2>SQL SERVER</h2>
</asp:content>

Any thoughts why I my inherent statement is not good enough? Thanks.
-Todd
 
I changed the code a little bit, I placed everything inside the code behind the webform so everything is being called from the same place and I'm no longer getting an error but the XML is not being called. Here is the code behind:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.ComponentModel
Imports System.IO
Imports System.Xml


Public Class WebForm2_aspx
Inherits System.Web.UI.Page
Protected Sub Page_Load()
Dim xml As New String(Me.GetXML(100100))
Console.Write(xml)

End Sub
Public Function GetXML(ByVal id As Integer) As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim toReturn As String
cnn = New SqlConnection("Data Source=SQLSERVER;Initial Catalog=upsizedCandidate;Integrated Security=SSPI")
cmd = New SqlCommand("Select xmltext FROM PATHfiles where id = 100100 ", cnn)

Try
toReturn = cmd.ExecuteScalar
Catch
Finally
cnn.Close()
cnn.Dispose()
End Try
Return toReturn
End Function
End Class

And here is my actual webform.aspx:

<%@ Page Language="VB" CodeFile="WebForm2.aspx.vb" Inherits="WebForm2_aspx" Title="WebForm2" %>
<asp:xml>
<h1>TEST!!</h1>
</asp:xml>


The only thing that comes up is TEST!!, the header. Any quick fix you know of that could solve this? Thanks again!
 
Code:
Console.Write(xml)
Perhaps if you were using a console application that would work but as this is an ASP.NET site, you'll need to write the contents out to a control on the page.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
toddw607 said:
Dim xml As New String(Me.GetXML(100100))
I don't think this is correct. instead it should be
Code:
Dim xml as string = Me.GetXML(100100)

also your previous posthas a few problems which is why inheritance wasn't working.

You named the base class newClass, but then WebForm2 inherits MyWebFrom. MyWebFrom doesn't exist. it's call newClass. Rename either MyWebForm or NewClass so they match. Also make this change in the Page declaration on WebForm2.aspx

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi guys,
Thanks for the responses. My code is as follows:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.ComponentModel
Imports System.IO
Imports System.Xml


Public Class WebForm2_aspx
Inherits System.Web.UI.Page
Protected Sub Page_Load()
Dim xml As String = Me.GetXML(100100)
Console.Write(xml)

End Sub
Public Function GetXML(ByVal id As Integer) As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim toReturn As String
cnn = New SqlConnection("Data Source=SQLSERVER;Initial Catalog=upsizedCandidate;Integrated Security=SSPI")
cmd = New SqlCommand("Select xmltext FROM PATHfiles where id = 100100 ", cnn)

Try
toReturn = cmd.ExecuteNonQuery

Catch
Finally
cnn.Close()
cnn.Dispose()

End Try
Return toReturn
End Function
End Class

ASP Webform:
<%@ Page Language="VB" Debug="true" CodeFile="WebForm2.aspx.vb" Inherits="WebForm2_aspx" Title="WebForm2" %>
<asp:xml>
<h1>TEST!!</h1>
</asp:xml>

What could I use to make it write out to a ASPX page? Don't I need a cmd.ExecuteNonQuery statement to make the SQL statement work? Sorry, I am really confused.
 
What could I use to make it write out to a ASPX page?
How about a Label or a Literal control.

I think you should take a few basic tutorials from (as a good starting point) and learn ASP.NET and how it works before tackling this project. Otherwise, you will run into problem after problem and end up asking a question for each one, which is already starting to happen.


____________________________________________________________
Mark,
[URL unfurl="true"]http://aspnetlibrary.com[/url]

Need help finding an answer? Try the Search Facility or read FAQ222-2244.
 
Ok, thanks for all your help Jason and ca8msm. Have a good day!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top