xml nodes have single attribute and are self closing, cannot "xmldatadoc.load()" to dataset. Suggestions?

Hi everyone,

I'm trying to "upgrade" my code on a xml load/config/save winform that I have used in the past to make simple changes.  I use a empty dataset, read the xml schema to dataset, create a new xml datadocument from dataset, and bind the datadocument to a datagrid.

The current code works fine when your xml nodes look like standard elements:  <x>value</x> (which 99% of mine thus far have)

Im trying to update the code so it will work with nodes having attributes: <x name="name"/>   *NOTE: No empty tags, ALL self closing*

Below is my original code. Below that is the XML file.  I cannot seem to get my dataset to reflect a structure like it once was/had, so I am looking to get suggestions on what to add. 

When attempting to read this xml with attributes, I end up with my datagrid being a 1x1 that has the first childnode's tag name as the column header, and the innerxml of that node is the column data. 


Is defining an external schema file going to handle this?  What about a DTD?

 

It seems silly that the earlier code of mine could read it into a dataset in five lines, yet adding a single attribute on the element mucks it all up.  I am sure I have overlooked something critical in my research. 

 

Private Sub syncdsanddatadoc()
If txtXMLFile.Text <> "" Then
Try

xmlds = New DataSet
' xmlds.ReadXml(txtXMLFile.Text)
xmlds.ReadXmlSchema(txtXMLFile.Text)
prechangedata = New Xml.XmlDataDocument(xmlds)
prechangedata.Load(txtXMLFile.Text)

DataGrid1.DataSource = prechangedata.DataSet.Tables("Scanner")
DataGrid1.AlternatingBackColor = Color.Gainsboro
DataGrid1.SelectionBackColor = Color.Green

DataGrid1.CaptionVisible = False
DataGrid1.Show()
Catch ex As Exception
MessageBox.Show("Error with XML file. Either it doesn't exist, or a bad bind occured." & vbCrLf & "details: " & ex.Message.ToString)
pLogToFile("
Error with XML file. Either it doesn't exist, or a bad bind occured. Details: " & ex.Message.ToString, 1)
End Try

End If
End Sub

Private Sub
btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
xmlds.WriteXml(txtXMLFile.Text)
System.Threading.Thread.Sleep(1000)
DataGrid1.Refresh()
btnSave.BackColor = Color.Green
MessageBox.Show("Changes have been saved to xml file at " & txtXMLFile.Text.ToString)
btnSave.BackColor = Color.Gainsboro
Catch ex As Exception
MsgBox("Did not save. Make changes manually.", MsgBoxStyle.Exclamation, "Did not save.")
pLogToFile("Error occured while saving XML data: " & ex.Message.ToString, 1)
btnSave.BackColor = Color.Pink
End Try
End Sub

  

<ConfigSettings>
<Scanner>
<SQLServer connString="xxxxx" />
<IpAddress name="localhost" />
<HostPort name="20002" />
<ServiceName name="CAMS-Receiving" />
</Scanner>
</ConfigSettings>
 

Final Question:

- is there a way to format this code so that it will handle both attributes and elements in my read?  Or, will I have to run a second version of this code and just know beforehand the structure of my XML doc.  *I would like to be able to open and save ANY xml file with this when i'm done* (or at least tick a box to indicate an alternate read method)
 


.net developer - Charlotte, NC
0
Twood
3/17/2008 9:26:00 PM
asp.net.xml-datasource 7181 articles. 0 followers. Follow

8 Replies
362 Views

Similar Articles

[PageSpeed] 45

i tried it using Grid View and it is working for me..

Below is xml is used..

<Names>

<Name >One</Name>

<Name est="One_est"/> <Name est="Two_est"/>

</Names>

Below is output i got.. 

est Name_Text
  One
One_est  
Two_est  

Thanks,

Kiran


Don't forget to click "Mark as Answer" on the post that helped you.
0
kalvagadda
3/17/2008 11:06:50 PM

 my issue is in the dataset, it's reading and splitting each node into it's own datatable.

 I tried using merge() on the dataset but that did not help.
 


.net developer - Charlotte, NC
0
Twood
3/18/2008 1:59:52 PM

Hi Twood,

Not all the schema of one special xml document are understanded by DataGrid control. You'd better use xslt to transform the xml first.

To learn xslt : http://www.w3schools.com/xsl/xsl_languages.asp

 Here is one post similar to yours.

http://forums.asp.net/t/1216730.aspx

 



Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
3/19/2008 2:03:25 AM

 Hi Samu,

 Thank you for the link.  I will read and try my coding again.
 


.net developer - Charlotte, NC
0
Twood
3/19/2008 12:51:29 PM

 Hi Samu,


I've created xsl files to help transform my xml files as you suggested and they display correct when opened in a browser.

when I call my readXML then bind to the gridview it is not "transforming" it for me.  Do i have to manually tell it to use the xsl file? I thought by adding a reference to the xsl in the xml file it did this automatically?  I'm choosing different xml files to view at runtime so I cannot hardcode a transform file on the xmldatasource. So I am not using it, and instead just using a dataset, xmldatadocument, and gridview.

Maybe I am using the wrong controls to work with this xml. Would creating a new xmldocument object and using the xmldatasource suit my needs better? 


My page needs to be as plain vanilla as possible so that I can use it to view, edit, and then re-save all the different XML files I have in production. Any suggestions you have would be very helpful.

.net developer - Charlotte, NC
0
Twood
3/19/2008 5:01:10 PM

I've reworked this project and have made a lot more progress.  Using the code below I am able to preform my transform but when I assign gridview.datasource = xmldatasource1 I get an error that "did not have any properties or attributes from which to generate columns".I need to be able to make that transformation, assign results to a editable gridview, and then save any changes back to the xmldocument.

I've noticed that my xmldatasource1.data has "<html><table> etc" in it.  Which may explain some of the issues I have encountered.

I have to focus on some other coding tasks for now, but I hope some of you experts here can recommend some things for me to try so that I can make some time in a week or two to work on this.   

 I would like to get this to work with one of my xml files, then rework the code and maintain flexibility.  At it's most boiled down functionality this is just a xml file view/save interface.  It's just very important that it can handle differing structures of xml using the xsl I will create for it.

 

UPDATED CODE (xml and xsl files at bottom)

 

Imports System.io
Imports System.xml
Partial Class _Default
Inherits System.Web.UI.Page

Const FILEPATH As String = "C:\Mantissa\Production\XML\" Public xst As Xsl.XslCompiledTransform


Private Sub LoadXMLtoDDL()
Try 'Begin populating if id has been entered Dim dirPath As DirectoryInfo = New DirectoryInfo(FILEPATH)
If dirPath.Exists() = False Then dirPath.Create() End If
Dim
dirInfo As New DirectoryInfo(dirPath.ToString())
ddlXML.DataSource = dirInfo.GetFiles("*.xml")
ddlXML.DataBind()


Catch ex As Exception

End Try
End Sub

Protected Sub
ddlXML_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlXML.SelectedIndexChanged
If ddlXML.SelectedValue <> "Select Item" Then
Try
Dim
xmldocument As New System.Xml.XmlDocument

xmldocument.Load(FILEPATH & ddlXML.SelectedValue)

Dim value As String = ddlXML.SelectedValue
value = "CAMS-Receiving-Settings"
'hack: ^^until I can reverse substring and change extension to .xsl xst = New Xsl.XslCompiledTransform
xst.Load(FILEPATH & value & ".xsl")


Dim sb As New StringBuilder(5000)
Dim sw As New StringWriter(sb)

xst.Transform(FILEPATH & ddlXML.SelectedValue, Nothing, sw)

XmlDataSource1.Data = sb.ToString
'contents of xmldatasource1.data = <html> <table> etc...


'throws the error that "did not have any properties or attributes from which to generate columns"
gvXMLfile.DataSource = XmlDataSource1 gvXMLfile.DataBind() gvXMLfile.Visible = True ' treeview1.DataBind()
'treeview.d()
'treeview1.Visible = True
Catch ex As Exception
exlogger(ex)
End Try

End If
End Sub

Protected Sub
Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (IsPostBack) Then LoadXMLtoDDL() End If


End Sub


End Class
 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>XML Edit</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlXML" runat="server" AutoPostBack="true">
</asp:DropDownList>
<br />
<asp:GridView ID="gvXMLfile" runat="server" BackColor="white">
<RowStyle HorizontalAlign="center" Font-Size=".7em" Wrap="false" />
<AlternatingRowStyle BackColor="silver" Wrap="false" Font-Size=".7em" HorizontalAlign="center" />
<HeaderStyle BackColor="black" ForeColor="white" Font-Size=".7em" Wrap="false" HorizontalAlign="center" />
<FooterStyle BackColor="black" ForeColor="white" Font-Size=".7em" Wrap="false" Font-Bold="true" HorizontalAlign="center" />
</asp:GridView>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource>

</div>
</form>
</body>
</html>
   
<ConfigSettings>
<Scanner>
<SQLServer connString="user id=xx;password=xxxxxx;initial catalog=xx;data source=(local);Connect Timeout=4" />
<IpAddress name="localhost" />
<HostPort name="20002" />
<ServiceName name="CAMS-Receiving" />
</Scanner>
</ConfigSettings>




<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>CAMS-Receiving-Settings</h2>
<table border="1">
<tr bgcolor="#9D9D9D">
<th>IP Address</th>
<th>HostPort</th>
<th>ServiceName</th>
</tr>
<tr>
<td><xsl:value-of select="ConfigSettings/Scanner/IpAddress/@name"/></td>
<td><xsl:value-of select="ConfigSettings/Scanner/HostPort/@name"/></td>
<td><xsl:value-of select="ConfigSettings/Scanner/ServiceName/@name"/></td>
</tr>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>
 
  
.net developer - Charlotte, NC
0
Twood
3/19/2008 8:31:46 PM

Hi Twood ,

 

<html>
  <body>
    <h2>CAMS-Receiving-Settings</h2>
    <table border="1">
      <tr bgcolor="#9D9D9D">
        <th>IP Address</th>
        <th>HostPort</th>
        <th>ServiceName</th>
      </tr>
      <tr>
        <td>localhost</td>
        <td>20002</td>
        <td>CAMS-Receiving</td>
      </tr>
    </table>
  </body>
</html>
 

Unfortunately, this xml file can not be recognized by gridview.

So you need to change gridview control to this:

 

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="XmlDataSource1" Width="259px">
            <Columns>
            
                <asp:TemplateField  >
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# XPath("td[1]") %>'></asp:Label>
                    </ItemTemplate>
                    <HeaderTemplate>
                        <asp:Label ID="Label2" runat="server" Text='' Width="169px"></asp:Label>
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# XPath("td[2]") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# XPath("td[3]") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
 

 

But there is no way to show head text using above code.

So if you can change your xsl file to transform xml file to the schema like below xml file , it will be easier for gridview to show it.

<persons>
  <person firstname="samu" lastname="zhang" />
</persons>
 

Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
3/20/2008 4:04:29 AM

Thanks once again Samu!

This gets me much further, and shows me the implementations I need to get this finished.

Many thanks! 


.net developer - Charlotte, NC
0
Twood
3/20/2008 1:25:00 PM
Reply:

Similar Artilces:

superreview granted: [Bug 444994] In <folderWidgets.xml>, "Error: aFolder is null", loading "Junk Settings" panel : [Attachment 333894] Fix regression per Neil's suggestion
neil@parkwaycc.co.uk <neil@httl.net> has granted Kent James (:rkent) <kent@caspia.com>'s request for superreview: Bug 444994: In <folderWidgets.xml>, "Error: aFolder is null", loading "Junk Settings" panel https://bugzilla.mozilla.org/show_bug.cgi?id=444994 Attachment 333894: Fix regression per Neil's suggestion https://bugzilla.mozilla.org/attachment.cgi?id=333894&action=edit ...

superreview requested: [Bug 444994] In <folderWidgets.xml>, "Error: aFolder is null", loading "Junk Settings" panel : [Attachment 333894] Fix regression per Neil's suggestion
Kent James (:rkent) <kent@caspia.com> has asked neil@parkwaycc.co.uk <neil@httl.net> for superreview: Bug 444994: In <folderWidgets.xml>, "Error: aFolder is null", loading "Junk Settings" panel https://bugzilla.mozilla.org/show_bug.cgi?id=444994 Attachment 333894: Fix regression per Neil's suggestion https://bugzilla.mozilla.org/attachment.cgi?id=333894&action=edit ------- Additional Comments from Kent James (:rkent) <kent@caspia.com> So this is what you had in mind, right? ...

Is there a way to write Atlas "text/xml-script" script Into single file like ".js" or ".css" file
I have tried the following code: <script type="text/xml-script" src="Default.aspx.ajax"><script type="text/xml-script" src="Default.aspx.js"><script type="text/xml-script" src="Default.xml"> but they dit dot work. thanks.msn & email:lidong6@gmail.com I believe it does not work as the XML-Script processor takes the content within the script tags to do processing and ignores the src tag. I think this will be a nice feature to add in the next release....

Setting xml attribute "use=required" property when generating xml from PDM
I am generating an XML schema from a physical data model, and had hoped that the attributes generated would have the property "use=required" set, if the column in the related table was set to mandatory. However, this does not happen. Can anyone advise me how to get this property set, or would I have to use an Extended Model Definition to achieve this? And if so, any suggestions on how to go about getting this done? Thanks Guy ...

superreview requested: [Bug 251274] Error: [Exception... "Node was not found" code: "8" nsresult: "0x80530008 (NS_ERROR_DOM_NOT_FOUND_ERR)" location: "chrome://inspector/content/inspector.xml Line:
Boris Zbarsky <bzbarsky@mit.edu> has asked neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> for superreview: Bug 251274: Error: [Exception... "Node was not found" code: "8" nsresult: "0x80530008 (NS_ERROR_DOM_NOT_FOUND_ERR)" location: "chrome://inspector/content/inspector.xml Line: 684"] https://bugzilla.mozilla.org/show_bug.cgi?id=251274 Attachment 193251: Fix https://bugzilla.mozilla.org/attachment.cgi?id=193251&action=edit ------- Additional Comments from Boris Zbarsky <bzbarsky@mit.edu> This just makes su...

superreview granted: [Bug 251274] [FIX]Error: [Exception... "Node was not found" code: "8" nsresult: "0x80530008 (NS_ERROR_DOM_NOT_FOUND_ERR)" location: "chrome://inspector/content/inspector.xml Lin
neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> has granted Boris Zbarsky <bzbarsky@mit.edu>'s request for superreview: Bug 251274: [FIX]Error: [Exception... "Node was not found" code: "8" nsresult: "0x80530008 (NS_ERROR_DOM_NOT_FOUND_ERR)" location: "chrome://inspector/content/inspector.xml Line: 684"] https://bugzilla.mozilla.org/show_bug.cgi?id=251274 Attachment 193251: Fix https://bugzilla.mozilla.org/attachment.cgi?id=193251&action=edit ------- Additional Comments from neil@parkwaycc.co.uk <neil.parkwa...

XML "Reader" that allows me to access specific nodes and attributes efficiently?
Hi, I'm pretty much a newcomer when it comes to XML Development and I'm hoping you can help me. The application I've inherited is a bit of a mess because SQL statements are littered all over the place, making it difficult to find, tune and reuse queries as well as validating them in a semi automated way. Besides, if we wanted to support SQL Server as well as Oracle, we'd have no way of storing the different forms of the query. So I've started creating an XML file to move all the SQL into. The current draft XML looks something like:   <?xml version="1.0" ?> &nb...

suggestion: "Close Tabs to the Left", "Close Tabs to the Right"
I would find it useful if in addition to the "Close Other Tabs" command, there were a way to "Close Tabs to the Left" and "Close Tabs to the Right" when you right-click on a particular tab. Particularly when I've exhausted a train of thought that might consist of a number of tabs, it'd be nice to be able to just close all tabs to the right of the last tab before that train of thought. This may be peculiar to the way I abuse tabs but I'm just throwing it out there in case I'm not alone. ...

When is "close" not really "close"
I've had a strange thing occur a couple of times. When I leave at night, I leave my computer on, but close Thunderbird. That way, I can VPN in from home and view the mail store, but still access e-mail through POP3. One night, a week or so ago, I checked POP3 from home and noticed the mailbox was empty. That's impossible; I get about 500 messages a day. So, I took control of my desktop session and looked around. Thunderbird was not visible, but it was still running in the background. I have since determined that if I close it with the "X" icon at upper ...

superreview requested: [Bug 428847] XML Parsing Error with ":" in href attribute of xml-stylesheet processing instruction : [Attachment 316114] Fix, with tests.
Johnny Stenback (:jst) <jst@mozilla.org> has asked Jonas Sicking (:sicking) <jonas@sicking.cc> for superreview: Bug 428847: XML Parsing Error with ":" in href attribute of xml-stylesheet processing instruction https://bugzilla.mozilla.org/show_bug.cgi?id=428847 Attachment 316114: Fix, with tests. https://bugzilla.mozilla.org/attachment.cgi?id=316114&action=edit ...

superreview granted: [Bug 428847] XML Parsing Error with ":" in href attribute of xml-stylesheet processing instruction : [Attachment 316114] Fix, with tests.
Jonas Sicking (:sicking) <jonas@sicking.cc> has granted Johnny Stenback (:jst) <jst@mozilla.org>'s request for superreview: Bug 428847: XML Parsing Error with ":" in href attribute of xml-stylesheet processing instruction https://bugzilla.mozilla.org/show_bug.cgi?id=428847 Attachment 316114: Fix, with tests. https://bugzilla.mozilla.org/attachment.cgi?id=316114&action=edit ...

"Attempt to use an "XML" extension that has not been registered..."
Hello, I am using Reporting Service in server mode.I currently have a report in which in include a few subreports. All of them use the same datasource (sqlserver 2005 database connectionstring)I have to add another report which is based on XML data. To do so, I created a new shared datasource, designed my query, added the report parameters, tested the query... This works but when I try to deploy this report on the report server I am getting an error I do not understand:"Attemps to use an "XML" extension of data that has not been registered for this report server"I do...

superreview denied: [Bug 444994] In <folderWidgets.xml>, "Error: aFolder is null", loading "Junk Settings" panel : [Attachment 333790] Stop nulling variables
neil@parkwaycc.co.uk <neil@httl.net> has denied Kent James (:rkent) <kent@caspia.com>'s request for superreview: Bug 444994: In <folderWidgets.xml>, "Error: aFolder is null", loading "Junk Settings" panel https://bugzilla.mozilla.org/show_bug.cgi?id=444994 Attachment 333790: Stop nulling variables https://bugzilla.mozilla.org/attachment.cgi?id=333790&action=edit ------- Additional Comments from neil@parkwaycc.co.uk <neil@httl.net> No, I don't think this is right. ...

XML to DataSet "kind of" works...
I need a little help with XML... I have an XML file 'products.xml' that gets updated 4 times a day. Our ASP.net application hits up the XML file every hour. This is how the XML looks like... <Product ID="3829173"> <Name>Purple Cow</Name> <Desc>Blah blah blah</Desc> <Quantity>5</Quantity> <PricingLevels> <Regular>9.99</Regular> <Valued>8.99</Valued> <Employee>4.99</Employee> </PricingLevels> </Product> When I bind the XM...

Web resources about - xml nodes have single attribute and are self closing, cannot "xmldatadoc.load()" to dataset. Suggestions? - asp.net.xml-datasource

Resources last updated: 12/22/2015 1:29:06 AM