Search Results

Search found 71 results on 3 pages for 'readxml'.

Page 1/3 | 1 2 3  | Next Page >

  • Some Problem In Using DataSet.ReadXML

    - by Chong
    hi friends, i want to use dataset.readxml for retrieve some data from xml file.But,my xml format is not well format,one part is for dataset and another part for other things.so,how i retrieve the dataset part.i am developing in c#.net 2008.xml file format is like below. <Object type="Sample"> <Object type="Tool"> <Property name="Text">Prescription1</Property> <Property name="Name">Prescription1</Property> <Object type="TextBox"> <Property name="Text">Singapore</Property> <Property name="Name">TextBox2</Property> </Object> <DataSet> //This Part <TableOne> <ItemID>001</ItemID> <ItemName>Item001</ItemName> <Price>100</Price> </TableOne> <TableOne> <ItemID>002</ItemID> <ItemName>Item002</ItemName> <Price>200</Price> </TableOne> </DataSet> </Object> regards Chong

    Read the article

  • myXmlDataDoc.DataSet.ReadXml problem

    - by alex
    Hi: I am using myXmlDataDoc.DataSet.ReadXml(xml_file_name, XmlReadMode.InferSchema); to populate the tables within the dataset created by reading in a xml schema using: myStreamReader = new StreamReader(xsd_file_name); myXmlDataDoc.DataSet.ReadXmlSchema(myStreamReader); The problems I am facing is when it comes to read the xml tag: The readXml function puts the element in a different table and everything in the tables are 0s. Here is the print out of the datatable: TableName: test_data 100 2 1 TableName: parameters 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10 0 11 0 12 0 In my xsd file, I represent an array using this: <xs:element name="test_data"> <xs:complexType> <xs:complexContent> <xs:extension base="test_base"> <xs:sequence> <xs:element name="a" type="xs:unsignedShort"/> <xs:element name="b" type="xs:unsignedShort"/> <xs:element name="c" type="xs:unsignedInt"/> <xs:element name="parameters" minOccurs="0" maxOccurs="12" type="xs:unsignedInt"/> </xs:sequence> </xs:extension> </xs:complexContent> </xs:complexType> And here is my xml file: 100 2 1 1 2 3 4 5 6 7 8 9 10 11 12 I am expecting after the readXml function call, the "parameters" is part of the test_data table. TableName: test_data 100 2 1 1 2 3 4 5 6 7 8 9 10 11 12 Does anyone knows what's wrong? Thanks

    Read the article

  • DataTable ReadXmlSchema and ReadXml Resulting in error

    - by MasterMax1313
    I'm having some trouble with the ReadXmlSchema and ReadXml methods for a DataTable. I'm getting the error "DataTable does not support schema inference from Xml". Code Snippet: I've tried Table.ReadXmlSchema(new StringReader(File.ReadAllText(XsdFilePath))); Table.ReadXml(new StringReader(File.ReadAllText(XmlFilePath))); And Table.ReadXmlSchema(XsdFilePath); Table.ReadXml(XmlFilePath); Xml Snippet: <ScreenSets> <ScreenSet id="Credit 1"> <Screen xmlFile="sb-credit1.en.xml" tabText="Recommendation" isCached="false"> <Buttons> <Button id="btnClosePresentation"/> </Buttons> </Screen> </ScreenSet> <ScreenSet id="Credit 2"> <Screen xmlFile="sb-credit2.en.xml" tabText="Recommendation" isCached="false"> <Buttons> <Button id="btnClosePresentation"/> </Buttons> </Screen> </ScreenSet> <ScreenSet id="Credit 3"> <Screen xmlFile="sb-credit3.en.xml" tabText="Recommendation" isCached="false"> <Buttons> <Button id="btnClosePresentation"/> </Buttons> </Screen> </ScreenSet> </ScreenSets> Xsd: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="ScreenSets"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="ScreenSet"> <xs:complexType> <xs:sequence> <xs:element name="Screen"> <xs:complexType> <xs:sequence> <xs:element name="Buttons"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="Button"> <xs:complexType> <xs:attribute name="id" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="xmlFile" type="xs:string" use="required" /> <xs:attribute name="tabText" type="xs:string" use="required" /> <xs:attribute name="isCached" type="xs:boolean" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="id" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

    Read the article

  • Dataset.ReadXml() - Invalid character in the given encoding

    - by NLV
    Hello all I have saved a dataset in the sql database in an xml column using the following code. XmlDataDocument dd = new XmlDataDocument(dataset); and passing this xml document as sql parameter using param.value = new XmlNodeReader(dd); The XML is like <NewDataSet><SubContractChangeOrders><AGCol>1</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>006</Contract_x0020_Number><ContractID>30</ContractID><ChangeOrderID>211</ChangeOrderID><Amount>0.0000</Amount><Udf_CostReimbursableFlag>false</Udf_CostReimbursableFlag><Udf_CustomerCode /><Udf_SubChangeOrderStatus /></SubContractChangeOrders><SubContractChangeOrders><AGCol>2</AGCol><SCO_x0020_Number>002</SCO_x0020_Number><Contract_x0020_Number>006</Contract_x0020_Number><ContractID>30</ContractID><ChangeOrderID>212</ChangeOrderID><Amount>0.0000</Amount><Udf_CostReimbursableFlag>false</Udf_CostReimbursableFlag></SubContractChangeOrders><SubContractChangeOrders><AGCol>3</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>111</Contract_x0020_Number><ContractID>87</ContractID><ChangeOrderID>12</ChangeOrderID><Amount>300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>4</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>222</Contract_x0020_Number><ContractID>80</ContractID><ChangeOrderID>6</ChangeOrderID><Amount>100.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>5</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>777</Contract_x0020_Number><ContractID>79</ContractID><ChangeOrderID>5</ChangeOrderID><Amount>200.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>6</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>786</Contract_x0020_Number><ContractID>77</ContractID><ChangeOrderID>3</ChangeOrderID><Amount>100.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>7</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>787</Contract_x0020_Number><ContractID>78</ContractID><ChangeOrderID>4</ChangeOrderID><Amount>500.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>8</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 009</Contract_x0020_Number><ContractID>219</ContractID><ChangeOrderID>78</ChangeOrderID><Amount>9000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>9</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 010</Contract_x0020_Number><ContractID>220</ContractID><ChangeOrderID>79</ChangeOrderID><Amount>13000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>10</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 012</Contract_x0020_Number><ContractID>222</ContractID><ChangeOrderID>83</ChangeOrderID><Amount>2300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>11</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 020</Contract_x0020_Number><ContractID>226</ContractID><ChangeOrderID>86</ChangeOrderID><Amount>5400.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>12</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 021</Contract_x0020_Number><ContractID>227</ContractID><ChangeOrderID>87</ChangeOrderID><Amount>2300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>13</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con001</Contract_x0020_Number><ContractID>208</ContractID><ChangeOrderID>72</ChangeOrderID><Amount>3000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>14</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con002</Contract_x0020_Number><ContractID>209</ContractID><ChangeOrderID>73</ChangeOrderID><Amount>400.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>15</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con003</Contract_x0020_Number><ContractID>210</ContractID><ChangeOrderID>74</ChangeOrderID><Amount>6000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>16</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con004</Contract_x0020_Number><ContractID>211</ContractID><ChangeOrderID>75</ChangeOrderID><Amount>9000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>17</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con005</Contract_x0020_Number><ContractID>213</ContractID><ChangeOrderID>76</ChangeOrderID><Amount>17000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>18</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Cont001</Contract_x0020_Number><ContractID>228</ContractID><ChangeOrderID>89</ChangeOrderID><Amount>2000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>19</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>PUR001</Contract_x0020_Number><ContractID>229</ContractID><ChangeOrderID>88</ChangeOrderID><Amount>1000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>20</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>PUR002</Contract_x0020_Number><ContractID>230</ContractID><ChangeOrderID>90</ChangeOrderID><Amount>3000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>21</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>SC-002</Contract_x0020_Number><ContractID>2</ContractID><ChangeOrderID>7</ChangeOrderID><Amount>200.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>22</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>SC-004</Contract_x0020_Number><ContractID>7</ContractID><ChangeOrderID>65</ChangeOrderID><Amount>1000.0000</Amount></SubContractChangeOrders></NewDataSet> I'm trying to read it back as follows using (SqlConnection con = new SqlConnection("Server=#####;Initial Catalog=#####;User ID=####;Pwd=########")) { using (SqlCommand com = new SqlCommand("select * from dbo.tbl_#####", con)) { using (SqlDataAdapter ada = new SqlDataAdapter(com)) { ada.Fill(dt); MemoryStream ms = new MemoryStream(); object contractXML1 = dt.Rows[0]["SCOXML1"]; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, contractXML1); ms.Seek(0, SeekOrigin.Begin); ds.ReadXml(ms); } } } I'm getting the following error Data at the root level is invalid. Line 1, position 6. Any ideas? NLV

    Read the article

  • help me "dry" out this .net XML serialization code

    - by Sarah Vessels
    I have a base collection class and a child collection class, each of which are serializable. In a test, I discovered that simply having the child class's ReadXml method call base.ReadXml resulted in an InvalidCastException later on. First, here's the class structure: Base Class // Collection of Row objects [Serializable] [XmlRoot("Rows")] public class Rows : IList<Row>, ICollection<Row>, IEnumerable<Row>, IEquatable<Rows>, IXmlSerializable { public Collection<Row> Collection { get; protected set; } public void ReadXml(XmlReader reader) { reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new Row(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } } Derived Class // Acts as a collection of SpecificRow objects, which inherit from Row. Uses the same // Collection<Row> that Rows defines which is fine since SpecificRow : Row. [Serializable] [XmlRoot("MySpecificRowList")] public class SpecificRows : Rows, IXmlSerializable { public new void ReadXml(XmlReader reader) { // Trying to just do base.ReadXml(reader) causes a cast exception later reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new SpecificRow(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } public new Row this[int index] { // The cast in this getter is what causes InvalidCastException if I try // to call base.ReadXml from this class's ReadXml get { return (Row)Collection[index]; } set { Collection[index] = value; } } } And here's the code that causes a runtime InvalidCastException if I do not use the version of ReadXml shown in SpecificRows above (i.e., I get the exception if I just call base.ReadXml from within SpecificRows.ReadXml): TextReader reader = new StringReader(serializedResultStr); SpecificRows deserializedResults = (SpecificRows)xs.Deserialize(reader); SpecificRow = deserializedResults[0]; // this throws InvalidCastException So, the code above all compiles and runs exception-free, but it bugs me that Rows.ReadXml and SpecificRows.ReadXml are essentially the same code. The value of XmlNodeName and the new Row()/new SpecificRow() are the differences. How would you suggest I extract out all the common functionality of both versions of ReadXml? Would it be silly to create some generic class just for one method? Sorry for the lengthy code samples, I just wanted to provide the reason I can't simply call base.ReadXml from within SpecificRows.

    Read the article

  • Read [for xml auto, elements] into DataTable in ADO.NET

    - by ihorko
    Hello All! I have MS SQL Server stored procedure that returns XML (it uses SELECT with for xml auto, elements) I tried read it into DataTable: DataTable retTable = new DataTable(); SqlCommand comm = new SqlCommand("exec MySP", connection); SqlDataAdapter da = new SqlDataAdapter(comm); connection.Open(); da.Fill(retTable); but retTable contains 12 rows with separated full xml thar SQL Server returns. How can I read that XML from DB into DataTable object? Thanks!

    Read the article

  • DataSets and XML - The Simplistic Approach

    One of the first ways I learned how to read xml data from external data sources was by using a DataSet’s ReadXML function. This function takes file path for an XML document and then converts it to a Dataset. This functionality is great when you need a simple way to process an XML document.  In addition the DataSet object also offers a simple way to save data in an xml format by using the WriteXML function. This function saves the current data in the DataSet to an XML file to be used later. DataSet ds  = New DataSet();String filePath = “http://www.yourdomain.com/someData.xml”;String fileSavePath = “C:\Temp\Test.xml”//Read file for this locationds.readxml(filePath);//Save file to this locationds.writexml(fileSavePath); I have used the ReadXML function before when consuming data from external Rss feeds to display on one of my sites.  It allows me to quickly pull in data from external sites with little to no processing. Example site: MyCreditTech.com

    Read the article

  • Error Handling Examples(C#)

    “The purpose of reviewing the Error Handling code is to assure that the application fails safely under all possible error conditions, expected and unexpected. No sensitive information is presented to the user when an error occurs.” (OWASP, 2011) No Error Handling The absence of error handling is still a form of error handling. Based on the code in Figure 1, if an error occurred and was not handled within either the ReadXml or BuildRequest methods the error would bubble up to the Search method. Since this method does not handle any acceptations the error will then bubble up the stack trace. If this continues and the error is not handled within the application then the environment in which the application is running will notify the user running the application that an error occurred based on what type of application. Figure 1: No Error Handling public DataSet Search(string searchTerm, int resultCount) { DataSet dt = new DataSet(); dt.ReadXml(BuildRequest(searchTerm, resultCount)); return dt; } Generic Error Handling One simple way to add error handling is to catch all errors by default. If you examine the code in Figure 2, you will see a try-catch block. On April 6th 2010 Louis Lazaris clearly describes a Try Catch statement by defining both the Try and Catch aspects of the statement. “The try portion is where you would put any code that might throw an error. In other words, all significant code should go in the try section. The catch section will also hold code, but that section is not vital to the running of the application. So, if you removed the try-catch statement altogether, the section of code inside the try part would still be the same, but all the code inside the catch would be removed.” (Lazaris, 2010) He also states that all errors that occur in the try section cause it to stops the execution of the try section and redirects all execution to the catch section. The catch section receives an object containing information about the error that occurred so that they system can gracefully handle the error properly. When errors occur they commonly log them in some form. This form could be an email, database entry, web service call, log file, or just an error massage displayed to the user.  Depending on the error sometimes applications can recover, while others force an application to close. Figure 2: Generic Error Handling public DataSet Search(string searchTerm, int resultCount) { DataSet dt = new DataSet(); try { dt.ReadXml(BuildRequest(searchTerm, resultCount)); } catch (Exception ex) { // Handle all Exceptions } return dt; } Error Specific Error Handling Like the Generic Error Handling, Error Specific error handling allows for the catching of specific known errors that may occur. For example wrapping a try catch statement around a soap web service call would allow the application to handle any error that was generated by the soap web service. Now, if the systems wanted to send a message to the web service provider every time a soap error occurred but did not want to notify them if any other type of error occurred like a network time out issue. This would be varying tedious to accomplish using the General Error Handling methodology. This brings us to the use case for using the Error Specific error handling methodology.  The Error Specific Error handling methodology allows for the TryCatch statement to catch various types of errors depending on the type of error that occurred. In Figure 3, the code attempts to handle DataException differently compared to how it potentially handles all other errors. This allows for specific error handling for each type of known error, and still allows for error handling of any unknown error that my occur during the execution of the TryCatch statement. Figure 5: Error Specific Error Handling public DataSet Search(string searchTerm, int resultCount) { DataSet dt = new DataSet(); try { dt.ReadXml(BuildRequest(searchTerm, resultCount)); } catch (TimeoutException ex) { // Handle Timeout TimeoutException Only } catch (Exception) { // Handle all Exceptions } return dt; }

    Read the article

  • Proper way to implement IXmlSerializable?

    - by Greg
    Once a programmer decides to implement IXmlSerializable, what are the rules and best practices for implementing it? I've heard that GetSchema() should return null and ReadXml should move to the next element before returning. Are these true? And what about WriteXml: should it write a root element for the object or is it assumed that the root is already written? How should child objects be treated and written. Here's a sample of what I have now. I'll update it as I get good responses. public class Calendar: IEnumerable<Gvent>, IXmlSerializable { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Calendar") { _Name = reader["Name"]; _Enabled = Boolean.Parse(reader["Enabled"]); _Color = Color.FromArgb(Int32.Parse(reader["Color"])); if (reader.ReadToDescendant("Event")) { while (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Event") { var evt = new Event(); evt.ReadXml(reader); _Events.Add(evt); } } reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Name", _Name); writer.WriteAttributeString("Enabled", _Enabled.ToString()); writer.WriteAttributeString("Color", _Color.ToArgb().ToString()); foreach (var evt in _Events) { writer.WriteStartElement("Event"); evt.WriteXml(writer); writer.WriteEndElement(); } } } public class Event : IXmlSerializable { public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Event") { _Title = reader["Title"]; _Start = DateTime.FromBinary(Int64.Parse(reader["Start"])); _Stop = DateTime.FromBinary(Int64.Parse(reader["Stop"])); reader.Read(); } } public void WriteXml(XmlWriter writer) { writer.WriteAttributeString("Title", _Title); writer.WriteAttributeString("Start", _Start.ToBinary().ToString()); writer.WriteAttributeString("Stop", _Stop.ToBinary().ToString()); } }

    Read the article

  • Issue allowing custom Xml Serialization/Deserialization on certain types of field

    - by sw1sh
    I've been working with Xml Serialization/Deserialization in .net and wanted a method where the serialization/deserialization process would only be applied to certain parts of an Xml fragment. This is so I can keep certain parts of the fragment in Xml after the deserialization process. To do this I thought it would be best to create a new class (XmlLiteral) that implemented IXmlSerializable and then wrote specific code for handling the IXmlSerializable.ReadXml and IXmlSerializable.WriteXml methods. In my example below this works for Serializing, however during the Deserialization process it fails to run for multiple uses of my XmlLiteral class. In my example below sTest1 gets populated correctly, but sTest2 and sTest3 are empty. I'm guessing I must be going wrong with the following lines but can't figure out why.. Any ideas at all? Private Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml Dim StringType As String = "" If reader.IsEmptyElement OrElse reader.Read() = False Then Exit Sub End If _src = reader.ReadOuterXml() End Sub Full listing: Imports System Imports System.Xml.Serialization Imports System.Xml Imports System.IO Imports System.Text Public Class XmlLiteralExample Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim MyObjectInstance As New MyObject MyObjectInstance.aProperty = "MyValue" MyObjectInstance.XmlLiteral1 = New XmlLiteral("<test1>Some Value</test1>") MyObjectInstance.XmlLiteral2 = New XmlLiteral("<test2>Some Value</test2>") MyObjectInstance.XmlLiteral3 = New XmlLiteral("<test3>Some Value</test3>") ' quickly serialize the object to Xml Dim sw As New StringWriter(New StringBuilder()) Dim s As New XmlSerializer(MyObjectInstance.[GetType]()), xmlnsEmpty As New XmlSerializerNamespaces xmlnsEmpty.Add("", "") s.Serialize(sw, MyObjectInstance, xmlnsEmpty) Dim XElement As XElement = XElement.Parse(sw.ToString()) ' XElement reads as the following, so serialization works OK '<MyObject> ' <aProperty>MyValue</aProperty> ' <XmlLiteral1> ' <test1>Some Value</test1> ' </XmlLiteral1> ' <XmlLiteral2> ' <test2>Some Value</test2> ' </XmlLiteral2> ' <XmlLiteral3> ' <test3>Some Value</test3> ' </XmlLiteral3> '</MyObject> ' quickly deserialize the object back to an instance of MyObjectInstance2 Dim MyObjectInstance2 As New MyObject Dim xmlReader As XmlReader, x As XmlSerializer xmlReader = XElement.CreateReader x = New XmlSerializer(MyObjectInstance2.GetType()) MyObjectInstance2 = x.Deserialize(xmlReader) Dim sProperty As String = MyObjectInstance2.aProperty ' equal to "MyValue" Dim sTest1 As String = MyObjectInstance2.XmlLiteral1.Text ' contains <test1>Some Value</test1> Dim sTest2 As String = MyObjectInstance2.XmlLiteral2.Text ' is empty Dim sTest3 As String = MyObjectInstance2.XmlLiteral3.Text ' is empty ' sTest3 and sTest3 should be populated but are not? xmlReader = Nothing End Sub Public Class MyObject Private _aProperty As String Private _XmlLiteral1 As XmlLiteral Private _XmlLiteral2 As XmlLiteral Private _XmlLiteral3 As XmlLiteral Public Property aProperty As String Get Return _aProperty End Get Set(ByVal value As String) _aProperty = value End Set End Property Public Property XmlLiteral1 As XmlLiteral Get Return _XmlLiteral1 End Get Set(ByVal value As XmlLiteral) _XmlLiteral1 = value End Set End Property Public Property XmlLiteral2 As XmlLiteral Get Return _XmlLiteral2 End Get Set(ByVal value As XmlLiteral) _XmlLiteral2 = value End Set End Property Public Property XmlLiteral3 As XmlLiteral Get Return _XmlLiteral3 End Get Set(ByVal value As XmlLiteral) _XmlLiteral3 = value End Set End Property Public Sub New() _XmlLiteral1 = New XmlLiteral _XmlLiteral2 = New XmlLiteral _XmlLiteral3 = New XmlLiteral End Sub End Class <System.Xml.Serialization.XmlRootAttribute(Namespace:="", IsNullable:=False)> _ Public Class XmlLiteral Implements IXmlSerializable Private _src As String Public Property Text() As String Get Return _src End Get Set(ByVal value As String) _src = value End Set End Property Public Sub New() _src = "" End Sub Public Sub New(ByVal Text As String) _src = Text End Sub #Region "IXmlSerializable Members" Private Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema Return Nothing End Function Private Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml Dim StringType As String = "" If reader.IsEmptyElement OrElse reader.Read() = False Then Exit Sub End If _src = reader.ReadOuterXml() End Sub Private Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml writer.WriteRaw(_src) End Sub #End Region End Class End Class

    Read the article

  • Problem with SIngleton Class

    - by zp26
    Hi, I have a prblem with my code. I have a viewController and a singleton class. When i call the method readXml and run a for my program update the UITextView. When i call the clearTextView method the program exit with EXC_BAD_ACCESS. The prblem it's the name of the variable position. This is invalid but i don't change anything between the two methods. You have an idea? My code: #import "PositionIdentifierViewController.h" #import "WriterXML.h" #import "ParserXML.h" #define timeToScan 0.1 @implementation PositionIdentifierViewController @synthesize accelerometer; @synthesize actualPosition; @synthesize actualX; @synthesize actualY; @synthesize actualZ; -(void)updateTextView:(NSString*)nomePosizione { NSString *string = [NSString stringWithFormat:@"%@",nomePosizione]; textEvent.text = [textEvent.text stringByAppendingString:@"\n"]; textEvent.text = [textEvent.text stringByAppendingString:string]; } -(IBAction)clearTextEvent{ textEvent.text = @""; //with this for my program exit for(int i=0; i<[[sharedController arrayPosition]count]; i++){ NSLog(@"sononelfor"); Position *tempPosition = [[Position alloc]init]; tempPosition = [[sharedController arrayPosition]objectAtIndex:i]; [self updateTextView:(NSString*)[tempPosition name]]; } } -(void)readXml{ if([sharedController readXml]){ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Caricamento Posizioni" message:@"Caricamento effettuato con successo" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; NSString *string = [NSString stringWithFormat:@"%d", [[sharedController arrayPosition]count]]; [self updateTextView:(NSString*)string]; //with only this the program is ok for(int i=0; i<[[sharedController arrayPosition]count]; i++){ NSLog(@"sononelfor"); Position *tempPosition = [[Position alloc]init]; tempPosition = [[sharedController arrayPosition]objectAtIndex:i]; [self updateTextView:(NSString*)[tempPosition name]]; } } else{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Caricamento Posizioni" message:@"Caricamento non riuscito" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [alert show]; [alert release]; } } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; sharedController = [SingletonController sharedSingletonController]; actualPosition = [[Position alloc]init]; self.accelerometer = [UIAccelerometer sharedAccelerometer]; self.accelerometer.updateInterval = timeToScan; self.accelerometer.delegate = self; actualX=0; actualY=0; actualZ=0; [self readXml]; } - (void)dealloc { [super dealloc]; [actualPosition dealloc]; [super dealloc]; } @end #import "SingletonController.h" #import "Position.h" #import "WriterXML.h" #import "ParserXML.h" #define standardSensibility 2 #define timeToScan .1 @implementation SingletonController @synthesize arrayPosition; @synthesize arrayMovement; @synthesize actualPosition; @synthesize actualMove; @synthesize stopThread; +(SingletonController*)sharedSingletonController{ static SingletonController *sharedSingletonController; @synchronized(self) { if(!sharedSingletonController){ sharedSingletonController = [[SingletonController alloc]init]; } } return sharedSingletonController; } -(BOOL)readXml{ ParserXML *newParser = [[ParserXML alloc]init]; if([newParser startParsing:(NSString*)@"filePosizioni.xml"]){ [arrayPosition addObjectsFromArray:[newParser arrayPosition]]; return TRUE; } else return FALSE; } -(id)init{ self = [super init]; if (self != nil) { arrayPosition = [[NSMutableArray alloc]init]; arrayMovement = [[NSMutableArray alloc]init]; actualPosition = [[Position alloc]init]; actualMove = [[Movement alloc]init]; stopThread = FALSE; } return self; } -(void) dealloc { [super dealloc]; } @end

    Read the article

  • Using a WPF ListView as a DataGrid

    - by psheriff
    Many people like to view data in a grid format of rows and columns. WPF did not come with a data grid control that automatically creates rows and columns for you based on the object you pass it. However, the WPF Toolkit can be downloaded from CodePlex.com that does contain a DataGrid control. This DataGrid gives you the ability to pass it a DataTable or a Collection class and it will automatically figure out the columns or properties and create all the columns for you and display the data.The DataGrid control also supports editing and many other features that you might not always need. This means that the DataGrid does take a little more time to render the data. If you want to just display data (see Figure 1) in a grid format, then a ListView works quite well for this task. Of course, you will need to create the columns for the ListView, but with just a little generic code, you can create the columns on the fly just like the WPF Toolkit’s DataGrid. Figure 1: A List of Data using a ListView A Simple ListView ControlThe XAML below is what you would use to create the ListView shown in Figure 1. However, the problem with using XAML is you have to pre-define the columns. You cannot re-use this ListView except for “Product” data. <ListView x:Name="lstData"          ItemsSource="{Binding}">  <ListView.View>    <GridView>      <GridViewColumn Header="Product ID"                      Width="Auto"               DisplayMemberBinding="{Binding Path=ProductId}" />      <GridViewColumn Header="Product Name"                      Width="Auto"               DisplayMemberBinding="{Binding Path=ProductName}" />      <GridViewColumn Header="Price"                      Width="Auto"               DisplayMemberBinding="{Binding Path=Price}" />    </GridView>  </ListView.View></ListView> So, instead of creating the GridViewColumn’s in XAML, let’s learn to create them in code to create any amount of columns in a ListView. Create GridViewColumn’s From Data TableTo display multiple columns in a ListView control you need to set its View property to a GridView collection object. You add GridViewColumn objects to the GridView collection and assign the GridView to the View property. Each GridViewColumn object needs to be bound to a column or property name of the object that the ListView will be bound to. An ADO.NET DataTable object contains a collection of columns, and these columns have a ColumnName property which you use to bind to the GridViewColumn objects. Listing 1 shows a sample of reading and XML file into a DataSet object. After reading the data a GridView object is created. You can then loop through the DataTable columns collection and create a GridViewColumn object for each column in the DataTable. Notice the DisplayMemberBinding property is set to a new Binding to the ColumnName in the DataTable. C#private void FirstSample(){  // Read the data  DataSet ds = new DataSet();  ds.ReadXml(GetCurrentDirectory() + @"\Xml\Product.xml");    // Create the GridView  GridView gv = new GridView();   // Create the GridView Columns  foreach (DataColumn item in ds.Tables[0].Columns)  {    GridViewColumn gvc = new GridViewColumn();    gvc.DisplayMemberBinding = new Binding(item.ColumnName);    gvc.Header = item.ColumnName;    gvc.Width = Double.NaN;    gv.Columns.Add(gvc);  }   // Setup the GridView Columns  lstData.View = gv;  // Display the Data  lstData.DataContext = ds.Tables[0];} VB.NETPrivate Sub FirstSample()  ' Read the data  Dim ds As New DataSet()  ds.ReadXml(GetCurrentDirectory() & "\Xml\Product.xml")   ' Create the GridView  Dim gv As New GridView()   ' Create the GridView Columns  For Each item As DataColumn In ds.Tables(0).Columns    Dim gvc As New GridViewColumn()    gvc.DisplayMemberBinding = New Binding(item.ColumnName)    gvc.Header = item.ColumnName    gvc.Width = [Double].NaN    gv.Columns.Add(gvc)  Next   ' Setup the GridView Columns  lstData.View = gv  ' Display the Data  lstData.DataContext = ds.Tables(0)End SubListing 1: Loop through the DataTable columns collection to create GridViewColumn objects A Generic Method for Creating a GridViewInstead of having to write the code shown in Listing 1 for each ListView you wish to create, you can create a generic method that given any DataTable will return a GridView column collection. Listing 2 shows how you can simplify the code in Listing 1 by setting up a class called WPFListViewCommon and create a method called CreateGridViewColumns that returns your GridView. C#private void DataTableSample(){  // Read the data  DataSet ds = new DataSet();  ds.ReadXml(GetCurrentDirectory() + @"\Xml\Product.xml");   // Setup the GridView Columns  lstData.View =      WPFListViewCommon.CreateGridViewColumns(ds.Tables[0]);  lstData.DataContext = ds.Tables[0];} VB.NETPrivate Sub DataTableSample()  ' Read the data  Dim ds As New DataSet()  ds.ReadXml(GetCurrentDirectory() & "\Xml\Product.xml")   ' Setup the GridView Columns  lstData.View = _      WPFListViewCommon.CreateGridViewColumns(ds.Tables(0))  lstData.DataContext = ds.Tables(0)End SubListing 2: Call a generic method to create GridViewColumns. The CreateGridViewColumns MethodThe CreateGridViewColumns method will take a DataTable as a parameter and create a GridView object with a GridViewColumn object in its collection for each column in your DataTable. C#public static GridView CreateGridViewColumns(DataTable dt){  // Create the GridView  GridView gv = new GridView();  gv.AllowsColumnReorder = true;   // Create the GridView Columns  foreach (DataColumn item in dt.Columns)  {    GridViewColumn gvc = new GridViewColumn();    gvc.DisplayMemberBinding = new Binding(item.ColumnName);    gvc.Header = item.ColumnName;    gvc.Width = Double.NaN;    gv.Columns.Add(gvc);  }   return gv;} VB.NETPublic Shared Function CreateGridViewColumns _  (ByVal dt As DataTable) As GridView  ' Create the GridView  Dim gv As New GridView()  gv.AllowsColumnReorder = True   ' Create the GridView Columns  For Each item As DataColumn In dt.Columns    Dim gvc As New GridViewColumn()    gvc.DisplayMemberBinding = New Binding(item.ColumnName)    gvc.Header = item.ColumnName    gvc.Width = [Double].NaN    gv.Columns.Add(gvc)  Next   Return gvEnd FunctionListing 3: The CreateGridViewColumns method takes a DataTable and creates GridViewColumn objects in a GridView. By separating this method out into a class you can call this method anytime you want to create a ListView with a collection of columns from a DataTable. SummaryIn this blog you learned how to create a ListView that acts like a DataGrid. You are able to use a DataTable as both the source of the data, and for creating the columns for the ListView. In the next blog entry you will learn how to use the same technique, but for Collection classes. NOTE: You can download the complete sample code (in both VB and C#) at my website. http://www.pdsa.com/downloads. Choose Tips & Tricks, then "WPF ListView as a DataGrid" from the drop-down. Good Luck with your Coding,Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS **Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".

    Read the article

  • IXmlSerializable Dictionary

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • IXmlSerializable Dictionary problem

    - by Shimmy
    I was trying to create a generic Dictionary that implements IXmlSerializable. Here is my trial: Sub Main() Dim z As New SerializableDictionary(Of String, String) z.Add("asdf", "asd") Console.WriteLine(z.Serialize) End Sub Result: <?xml version="1.0" encoding="utf-16"?><Entry key="asdf" value="asd" /> I placed a breakpoint on top of the WriteXml method and I see that when it stops, the writer contains no data at all, and IMHO it should contain the root element and the xml declaration. <Serializable()> _ Public Class SerializableDictionary(Of TKey, TValue) : Inherits Dictionary(Of TKey, TValue) : Implements IXmlSerializable Private Const EntryString As String = "Entry" Private Const KeyString As String = "key" Private Const ValueString As String = "value" Private Shared ReadOnly AttributableTypes As Type() = New Type() {GetType(Boolean), GetType(Byte), GetType(Char), GetType(DateTime), GetType(Decimal), GetType(Double), GetType([Enum]), GetType(Guid), GetType(Int16), GetType(Int32), GetType(Int64), GetType(SByte), GetType(Single), GetType(String), GetType(TimeSpan), GetType(UInt16), GetType(UInt32), GetType(UInt64)} Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) AttributableTypes.Contains(t) Private Shared ReadOnly IsKeyAttributable As Boolean = GetIsAttributable(GetType(TKey)) Private Shared ReadOnly IsValueAttributable As Boolean = GetIsAttributable(GetType(TValue)) Private Shared ReadOnly GetElementName As Func(Of Boolean, String) = Function(isKey) If(isKey, KeyString, ValueString) Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema Return Nothing End Function Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml For Each entry In Me writer.WriteStartElement(EntryString) WriteData(IsKeyAttributable, writer, True, entry.Key) WriteData(IsValueAttributable, writer, False, entry.Value) writer.WriteEndElement() Next End Sub Private Sub WriteData(Of T)(ByVal attributable As Boolean, ByVal writer As XmlWriter, ByVal isKey As Boolean, ByVal value As T) Dim name = GetElementName(isKey) If attributable Then writer.WriteAttributeString(name, value.ToString) Else Dim serializer As New XmlSerializer(GetType(T)) writer.WriteStartElement(name) serializer.Serialize(writer, value) writer.WriteEndElement() End If End Sub Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml Dim empty = reader.IsEmptyElement reader.Read() If empty Then Exit Sub Clear() While reader.NodeType <> XmlNodeType.EndElement While reader.NodeType = XmlNodeType.Whitespace reader.Read() Dim key = ReadData(Of TKey)(IsKeyAttributable, reader, True) Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False) Add(key, value) If Not IsKeyAttributable AndAlso Not IsValueAttributable Then reader.ReadEndElement() Else reader.Read() While reader.NodeType = XmlNodeType.Whitespace reader.Read() End While End While reader.ReadEndElement() End While End Sub Private Function ReadData(Of T)(ByVal attributable As Boolean, ByVal reader As XmlReader, ByVal isKey As Boolean) As T Dim name = GetElementName(isKey) Dim type = GetType(T) If attributable Then Return Convert.ChangeType(reader.GetAttribute(name), type) Else Dim serializer As New XmlSerializer(type) While reader.Name <> name reader.Read() End While reader.ReadStartElement(name) Dim value = serializer.Deserialize(reader) reader.ReadEndElement() Return value End If End Function Public Shared Function Serialize(ByVal dictionary As SerializableDictionary(Of TKey, TValue)) As String Dim sb As New StringBuilder(1024) Dim sw As New StringWriter(sb) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) xs.Serialize(sw, dictionary) sw.Dispose() Return sb.ToString End Function Public Shared Function Deserialize(ByVal xml As String) As SerializableDictionary(Of TKey, TValue) Dim xs As New XmlSerializer(GetType(SerializableDictionary(Of TKey, TValue))) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) Return xs.Deserialize(xr) xr.Close() End Function Public Function Serialize() As String Dim sb As New StringBuilder Dim xw = XmlWriter.Create(sb) WriteXml(xw) xw.Close() Return sb.ToString End Function Public Sub Parse(ByVal xml As String) Dim xr As New XmlTextReader(xml, XmlNodeType.Document, Nothing) ReadXml(xr) xr.Close() End Sub End Class

    Read the article

  • jaxb unmarshal problem

    - by Hoax
    private JAXBContext jaxbContext; private Marshaller marshaller; private Unmarshaller unmarshaller; private PoiList db; public XMLHandler() { try { JAXBContext.newInstance("x.y.shared"); } catch (JAXBException e) { e.printStackTrace(); } } public PoiList readXML() { try { unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(new XMLValidEventHandler()); db = (PoiList) unmarshaller.unmarshal(new File("src/source.xml")); } catch (JAXBException e) { e.printStackTrace(); } return db; } gets me this Exception in thread "main" java.lang.NullPointerException at com.sem.server.XMLHandler.readXML(XMLHandler.java:32) at sem.server.testDataAPI.main(testDataAPI.java:13) Line 32 in this case is the jaxbContext.createUnmarshaller() Line. packages are x.y.client x.y.server (includes the XMLHandler) x.y.shared (includes jaxb generated classes) not really sure what the problem is. any help is appreciated!

    Read the article

  • Convert XML to DataSet with rows

    - by lidermin
    Hi, I have an xml file like this: <result> <customer> <id>1</id> <name>A</name> </customer> <customer> <id>2</id> <name>B</name> </customer> </result> So I need that data filled on a DataSet, here is my code: var reader = new StringReader(xmldoc.InnerXml); dsDatos.ReadXml(reader); The problem is that it's filling the dataset with two Tables each one with a single row. But I need a single Table with the two rows. What am I doing wrong? PD: I'm using C# and I don't want to iterate through the XML file, I want to use the ReadXml method. Thanks for your time.

    Read the article

  • Counting elements and reading attributes with .net2.0 ?

    - by Prix
    I have an application that is on .net 2.0 and I am having some difficult with it as I am more use to linq. The xml file look like this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <updates> <files> <file url="files/filename.ext" checksum="06B9EEA618EEFF53D0E9B97C33C4D3DE3492E086" folder="bin" system="0" size="40448" /> <file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" /> <file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" /> </files> </updates> The file is downloaded and readed on the fly: XmlDocument readXML = new XmlDocument(); readXML.LoadXml(xmlData); Initially i was thinking it would go with something like this: XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("//files"); foreach (XmlNode node in nodes) { ... im reading it ... } But before reading them I need to know how many they are to use on my progress bar and I am also clueless on how to grab the attribute of the file element in this case. How could I count how many "file" ELEMENTS I have (count them before entering the foreach ofc) and read their attributes ? I need the count because it will be used to update the progress bar. Overall it is not reading my xml very well.

    Read the article

  • How to parse json string to dataset in C#

    - by Samir R. Bhogayta
    // Serialization of DataSet to json string StringWriter sw = new StringWriter(); versionUpGetData.WriteXml(sw, XmlWriteMode.WriteSchema); XmlDocument xd = new XmlDocument(); xd.LoadXml(sw.ToString()); String jsonText = JsonConvert.SerializeXmlNode(xd); File.WriteAllText(“d:/datasetJson.txt”,jsonText); //Deserialization of Json String to DataSet XmlDocument xd1 = new XmlDocument(); xd1 = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonText); DataSet jsonDataSet = new DataSet(); jsonDataSet.ReadXml(new XmlNodeReader(xd1));

    Read the article

  • .NET file Decryption - Bad Data

    - by Jon
    I am in the process of rewriting an old application. The old app stored data in a scoreboard file that was encrypted with the following code: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard(); } DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } This works fine. I have copied the code into my new app so that I can create a legacy loader and convert the data into the new format. The problem is I get a "Bad Data" error: System.Security.Cryptography.CryptographicException was unhandled Message="Bad Data.\r\n" Source="mscorlib" The error fires at this line: dTable.ReadXml(new StreamReader(cryptostreamDecr)); The encrypted file was created today on the same machine with the old code. I guess that maybe the encryption / decryption process uses the application name / file or something and therefore means I can not open it. Does anyone have an idea as to: A) Be able explain why this isn't working? B) Offer a solution that would allow me to be able to open files that were created with the legacy application and be able to convert them please? Here is the whole class that deals with loading and saving the scoreboard: using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.IO; using System.Data; using System.Xml; using System.Threading; namespace JawBreaker { [Serializable] class ScoreBoardLoader { private Jawbreaker jawbreaker; private String sSecretKey = @"?B?n?Mj?"; private String scoreBoardFileLocation = ""; private bool keepScoreBoardUpdated = true; private int intTimer = 180000; public ScoreBoardLoader(Jawbreaker jawbreaker, String scoreBoardFileLocation) { this.jawbreaker = jawbreaker; this.scoreBoardFileLocation = scoreBoardFileLocation; } // Call this function to remove the key from memory after use for security [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")] public static extern bool ZeroMemory(IntPtr Destination, int Length); // Function to Generate a 64 bits Key. private string GenerateKey() { // Create an instance of Symetric Algorithm. Key and IV is generated automatically. DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create(); // Use the Automatically generated key for Encryption. return ASCIIEncoding.ASCII.GetString(desCrypto.Key); } public void writeScoreboardToFile() { DataTable tempScoreBoard = getScoreboardFromFile(); //add in the new scores to the end of the file. for (int i = 0; i < jawbreaker.Scoreboard.Rows.Count; i++) { DataRow row = tempScoreBoard.NewRow(); row.ItemArray = jawbreaker.Scoreboard.Rows[i].ItemArray; tempScoreBoard.Rows.Add(row); } //before it is written back to the file make sure we update the sync info if (jawbreaker.SyncScoreboard) { //connect to webservice, login and update all the scores that have not been synced. for (int i = 0; i < tempScoreBoard.Rows.Count; i++) { try { //check to see if that row has been synced to the server if (!Boolean.Parse(tempScoreBoard.Rows[i].ItemArray[7].ToString())) { //sync info to server //update the row to say that it has been updated object[] tempArray = tempScoreBoard.Rows[i].ItemArray; tempArray[7] = true; tempScoreBoard.Rows[i].ItemArray = tempArray; tempScoreBoard.AcceptChanges(); } } catch (Exception ex) { jawbreaker.writeErrorToLog("ERROR OCCURED DURING SYNC TO SERVER UPDATE: " + ex.Message); } } } FileStream fsEncrypted = new FileStream(scoreBoardFileLocation, FileMode.Create, FileAccess.Write); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write); MemoryStream ms = new MemoryStream(); tempScoreBoard.WriteXml(ms, XmlWriteMode.WriteSchema); ms.Position = 0; byte[] bitarray = new byte[ms.Length]; ms.Read(bitarray, 0, bitarray.Length); cryptostream.Write(bitarray, 0, bitarray.Length); cryptostream.Close(); ms.Close(); //now the scores have been added to the file remove them from the datatable jawbreaker.Scoreboard.Rows.Clear(); } public void startPeriodicScoreboardWriteToFile() { while (keepScoreBoardUpdated) { //three minute sleep. Thread.Sleep(intTimer); writeScoreboardToFile(); } } public void stopPeriodicScoreboardWriteToFile() { keepScoreBoardUpdated = false; } public int IntTimer { get { return intTimer; } set { intTimer = value; } } public DataTable getScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardFileLocation); if (!f.Exists) { jawbreaker.writeInfoToLog("Scoreboard not there so creating new one"); return setupNewScoreBoard(); } else { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(sSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(sSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardFileLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } } public DataTable setupNewScoreBoard() { //scoreboard info into dataset DataTable scoreboard = new DataTable("scoreboard"); scoreboard.Columns.Add(new DataColumn("playername", System.Type.GetType("System.String"))); scoreboard.Columns.Add(new DataColumn("score", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("ballnumber", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("xsize", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("ysize", System.Type.GetType("System.Int32"))); scoreboard.Columns.Add(new DataColumn("gametype", System.Type.GetType("System.String"))); scoreboard.Columns.Add(new DataColumn("date", System.Type.GetType("System.DateTime"))); scoreboard.Columns.Add(new DataColumn("synced", System.Type.GetType("System.Boolean"))); scoreboard.AcceptChanges(); return scoreboard; } private void Run() { // For additional security Pin the key. GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned); // Remove the Key from memory. ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2); gch.Free(); } } }

    Read the article

  • C# file Decryption - Bad Data

    - by Jon
    Hi all, I am in the process of rewriting an old application. The old app stored data in a scoreboard file that was encrypted with the following code: private const String SSecretKey = @"?B?n?Mj?"; public DataTable GetScoreboardFromFile() { FileInfo f = new FileInfo(scoreBoardLocation); if (!f.Exists) { return setupNewScoreBoard(); } DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(SSecretKey); //Create a file stream to read the encrypted file back. FileStream fsread = new FileStream(scoreBoardLocation, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); DataTable dTable = new DataTable("scoreboard"); dTable.ReadXml(new StreamReader(cryptostreamDecr)); cryptostreamDecr.Close(); fsread.Close(); return dTable; } This works fine. I have copied the code into my new app so that I can create a legacy loader and convert the data into the new format. The problem is I get a "Bad Data" error: System.Security.Cryptography.CryptographicException was unhandled Message="Bad Data.\r\n" Source="mscorlib" The error fires at this line: dTable.ReadXml(new StreamReader(cryptostreamDecr)); The encrypted file was created today on the same machine with the old code. I guess that maybe the encryption / decryption process uses the application name / file or something and therefore means I can not open it. Does anyone have an idea as to: A) Be able explain why this isn't working? B) Offer a solution that would allow me to be able to open files that were created with the legacy application and be able to convert them please? Thank you

    Read the article

  • Avoiding Redundancies in XML documents

    - by MarceloRamires
    I was working with a certain XML where there were no redundancies <person> <eye> <eye_info> <eye_color> blue </eye_color> </eye_info> </eye> <hair> <hair_info> <hair_color> blue </hair_color> </hair_info> </hair> </person> As you can see, the sub-tag eye-color makes reference to eye in it's name, so there was no need to avoid redundancies, I could get the eye color in a single line after loading the XML into a dataset: dataset.ReadXml(path); value = dataset.Tables("eye_info").Rows(0)("eye_color"); I do realise it's not the smartest way of doing so, and this situation I'm having now wasn't unforeseen. Now, let's say I have to read xml's that are in this format: <person> <eye> <info> <color> blue </color> </info> </eye> <hair> <info> <color> blue </color> </info> </hair> </person> So If I try to call it like this: dataset.ReadXml(path); value = dataset.Tables("info").Rows(0)("color"); There will be a redundancy, because I could only go as far as one up level to identify a single field in a XML with my previous method, and the 'disambiguator' is three levels above. Is there a practical way to reach with no mistake a single field given all the above (or at least a few) fields ?

    Read the article

  • Reading XML by Dataset

    - by Sathish
    I using a dataset to read an xml file as shown below DataSet ds = new DataSet(); ds.ReadXml("C:\test.xml"); test.xml contains OMID Yes AssumptOMID int 10 ClientName Yes AssumptClient string 50 OppName Yes AssumptProjectName string 50 now i want to read fieldInfo in one dataset/datatable and settings in another dataset/datatable Please help me with the code

    Read the article

  • What is the best way to read and write cXML documents in C# ?

    - by tetranz
    I know this is a vague open ended question. I'm hoping to get some general direction. I need to add cXML punchout to an ASP.NET C# site / application. This is replacing something that I wrote years ago in ColdFusion. I'm a reasonably experienced C# developer but I haven't done much with XML. There seems to be lots of different options for processing XML in .NET. Here's the open ended question: Assuming that I have an XML document in some form, eg a file or a string, what is the best way to read it into my code? I want to get the data and then query databases etc. The cXML document size and our traffic volumes are easily small enough so that loading the a cXML document into memory is not a problem. Should I: 1) Manually build classes based on the dtd and use the XML Serializer? 2) Use a tool to generate classes. There are sample cXML files downloadable from Ariba.com. I tried xsd.exe to generate an xsd and then xsd.exe /c to generate classes. When I try to deserialize I get errors because there seems to be "confusion" around whether some elements should be single values or arrays. I tried the CodeXS online tool but that gives errors in it's log and errors if I try to deserialize a sample document. 2) Create a dataset and ReadXml()? 3) Create a typed dataset and ReadXml()? 4) Use Linq to XML. I often use Linq to Objects so I'm familiar with Linq in general but I'm struggling to see what it gives me in this situation. 5) Some other means. I guess I need to improve my understanding of XML in general but even so ... am I missing some obvious way of doing this? In the old ColdFusion site I found a free component ("tag") which basically ignored any schema and read the XML into a "structure" which is essentially a series of nested hash tables which was then easy to read in code. That was probably quite sloppy but it worked. I also need to generate XML files from my C# objects. Maybe Linq to XML will be good for that. I could start with a default "template" document and manipulate it before saving. Thanks for any pointers ...

    Read the article

1 2 3  | Next Page >