Posts

Showing posts with the label XML

Donate

How To Read XML File Using DataTable.ReadXml() In C#

Image
Good afternoon friends! In this tutorial, I will demonstrate how to read an XML file using DataTable's ReadXml() method. While reading a file using DataSet's ReadXml() method is straightforward, using the DataTable's method might cause run-time or logical bugs. One example is that when using the DataTable's ReadXml() function, the DataTable object does not contain any records or nothing at all given that fact that the method has successfully executed. To proceed, we will read an XML file below called books.xml taken from MSDN page using DataTable's ReadXml() method. <?xml version="1.0" encoding="utf-8" ?> <catalog> <book id= "bk101" > <author> Gambardella, Matthew </author> <title> XML Developer's Guide </title> <genre> Computer </genre> <price> 44.95 </price> <publish_date> 2000-10-01 </publish_date> <description&g

Serialize .NET Classes With Inheritance To XML In C#

Good day! Here's a simple example on how to Serialize .NET classes that applied the concept of Inheritance to XML. Given the model classes below: [Serializable] public class Employee { public int EmployeeId { get ; set ; } public string Name { get ; set ; } public string Address { get ; set ; } } [Serializable] public class Utility : Employee { public string Category { get ; set ; } } [Serializable] public class Supervisor : Employee { public int OverrideCode { get ; set ; } } The code to populate and serialize the objects to XML is presented here using XmlSerializer class: List<Employee> employees = new List<Employee>(); Supervisor supervisor1 = new Supervisor(); supervisor1.Name = "Michael" ; supervisor1.Address = "Manila" ; supervisor1.EmployeeId = 11111; supervisor1.OverrideCode = 234; employees.Add(supervisor1); Utility utility1 = new Utility(); utility1.Name = "Erick" ; utility1.Address = "Masba

Read SQL Server XML Data Type Column In C#.NET

Image
Hi all, In this demo, I have dummy XML files saved to an XML column in a table. The files have the same structure of nodes, except that some files have altered price value of 104.95. The is the structure of the dummy XML file. <catalog> <book id= "bk101" > <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description> An in-depth look at creating applications with XML. </description> </book> <book id= "bk102" > <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description> A former architect battles corporate zombies, an ev

XML parsing: line 1, character 38, unable to switch the encoding

Hello all, Given the task at hand that your going to insert XML data into an XML column in SQL Server and you encounter this error "XML parsing: line 1, character 38, unable to switch the encoding", it seems the insertion of XML data failed due to this line here: <?xml version="1.0" encoding="utf-8" ?> . After doing some research, I found a tutorial on how to avoid unicode issues when inserting XML data into an XML column in SQL Server which is the basis of the solution. I just change the Encoding of the stream to UTF8 to match the encoding of the XML file. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[ "DefaultConnection" ].ConnectionString)) { SqlCommand command = new SqlCommand( "Insert into XMLTable(name, xmlData) values (@name, @xmlData)" , con); con.Open(); string xmlFile = File.ReadAllText(location); using (MemoryStream stream = new MemoryStream()) { using (StreamWrite

Find Elements In XML From List Collection Using LINQ And C#

Hello, Given you have a List object with a number of string elements and you want to check whether the elements in the list are found in the XML file, options are your going to use the for each loop or the List.ForEach() action to traverse the List and perform searching through the XML file. XML File <?xml version="1.0" encoding="utf-8" ?> <catalog> <book id= "bk101" > <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description> An in-depth look at creating applications with XML. </description> </book> <book id= "bk102" > <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price>

How To Read Or Parse XML Using XDocument In LINQ And C#

Given the XML file below which is a sample popularized my Microsoft, here's how to traverse with that XML file using LINQ to XML XDocument class. XML File <?xml version="1.0" encoding="utf-8" ?> <catalog> <book id= "bk101" > <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description> An in-depth look at creating applications with XML. </description> </book> <book id= "bk102" > <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description> A former architect battles corporate zombies, an ev

Read Or Parse XML Using XPathDocument In C#

Good day! In this example, I will show you how to read an XML file using XPathNavigator and XPathDocument classes in .NET. When using these classes, make sure to include the System.Xml and System.Xml.XPath namespaces in your file. XML File <?xml version="1.0" encoding="utf-8" ?> <Invoice xmlns:inv= "http://salesorgchart.abcdefg.com" > <inv:Customers> <inv:TotalSales>134.49</inv:TotalSales> -<inv:Customer> <inv:Date>2013-11-15</inv:Date> <inv:Number>10001</inv:Number> <inv:CustomerName>Cherry Pie</inv:CustomerName> <inv:PONumber>30002</inv:PONumber> <inv:Address>Cebu City Philippines</inv:Address> -<inv:Products> -<inv:Product> <inv:Code>AE445</inv:Code> <inv:Category>Liquid Milk</inv:Category> <inv:Name>Devondale</inv:Name>

Show SQL Query Result As XML Using Sql Server FOR XML()

Image
Hello, Given that you are required to show the results of a query into an XML format, T-SQL has a function called For XML to achieve that output as shown below. Screenshot I have created two scripts to achieve the desired result as above. The first script will alias a column name with @AttributeName that signifies an attribute which will then be added to Assigned node using FOR XML Path() function. Use NorthwindCrudApp Go SELECT TOP 3 ProductID as "@ProductID" , ProductName as "@ProductName" , UnitsInStock as "@UnitsInStock" , UPPER (ProductName) as [text()] FROM Products As Products ORDER BY ProductID FOR XML PATH( 'Assigned' ), Root( 'DATA' ); The second script also creates column alias for each column using the syntax NodeName/@Attribute similar to an XPath expression. SELECT TOP 3 ProductID as "Assigned/@ProductID" , ProductName as "Assigned/@ProductName" , UnitsIn

Create XmlElement Using XmlSerializer In C#.NET

Image
Given the XML data below, the product properties are generated below the products node. What I want is to structure the product properties inside an element Product while serializing. <?xml version="1.0" encoding="utf-8"?> <Products xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd= "http://www.w3.org/2001/XMLSchema" > <Code>12345</Code> <Name>Samsung Galaxy</Name> <Model>Galaxy</Model> <Manufacturer>Samsung Ltd</Manufacturer> <OperatingSystem>Jelly Bean</OperatingSystem> <Distributor>Junrex</Distributor> <Version>7.0</Version> </Products> To achieve that, I have modified the model classes by separating the properties into another class and in the Products class I created a property of type List with XML Attribute Product . public class Products { [XmlElement("Product")] publ

The file references an XML namespace that is inconsistent with the target framework of the project. (Entity Framework 6)

Good day to all! When adding an ADO.NET Entity Data Model to a ASP.NET project which connects to a certain SQL Server database, the entities (tables) do not appear on the model design view. However, the model successfully connects to the SQL DB.Upon checking the Model design view, an error is shown which is "The file references an XML namespace that is inconsistent with the target framework of the project.". After debugging and re-doing the steps in adding Entity Data Model, the error still persists. Later, I found out that the ASP.NET project target framework was 4.0. Changing it to .NET Framework 4.5 solved the issue . Cheers!

The type of one of the expression in the join clause is incorrect.Type inference failed in the call to GroupJoin In C#

Hi, I just tested on grouping two collections using GroupJoin approach in LINQ to XML. In the example, the two collections are Customers and Companies. In which, companies served as grouping for the customers. In simple terms, identify a customer of which company he or she belongs. The code below produced an error The type of one of the expression in the join clause is incorrect.Type inference failed in the call to GroupJoin. XElement companiesAndCustomers = new XElement( "CompaniesAndCustomers" , from company in companies join customer in customers on company equals customer.CompanyName into groupCompany select new XElement( "Company" , new XAttribute( "CompanyName" , company.CompanyName), new XAttribute( "Country" , company.Country), from subCustomer in groupCompany select new XElement( "Customer" , subCustomer.LastN

Bind XML Node Value To GridView Column In ASP.NET Using XPath

Image
Given in a datasource object where in you have a column which contains an XML string and you want to bind a certain node value instead of the entire XML string to GridView column, here's a solution using XPath. ASPX: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <asp:GridView ID= "gvPersons" runat= "server" AutoGenerateColumns= "False" BackColor= "White" Width= "400px" BorderColor= "#E7E7FF" BorderStyle= "None" BorderWidth= "1px" CellPadding= "3" > <AlternatingRowStyle BackColor= "#F7F7F7" /> <Columns> <asp:BoundField DataField= "ID" HeaderText= "ID" > <ItemStyle Width= "50px" /> </asp:BoundField> <asp:BoundField DataField= "XMLData" HeaderText= "Name" > <ItemStyle Width= &quo

Validate XML against XSD File In C# And VB.NET

In my nature of work, we dealt with XML files and schema on a daily basis. And here's a cool snippet on validating XML file against and XSD file. C# using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; public class Form1 { private void Form1_Load(SystemObject sender, SystemEventArgs e) { XmlDocument myDocument = new XmlDocument(); myDocument.Load( "C:\\somefile.xml" ); myDocument.Schemas.Add( "namespace here or empty string" , "C:\\someschema.xsd" ); ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler); myDocument.Validate(eventHandler); } private void ValidationEventHandler( object sender, ValidationEventArgs e) { switch (e.Severity) { case XmlSeverityType.Error: Debug.WriteLine( "Error: {0}" , e.Message); break ; case

Generate Sample XML From XSD Using Visual Studio 2012

Image
There was a question on how to generate sample XML from an XSD without using C# or VB.NET Code. I did some googling for a few hours and then stumbled upon a tutorial from Code project which is the reference of this post. Since, Im using Visual Studio 2012, I replicated the steps based from the article. 1. Add a new XSD file to Visual Studio. In my case, I reused the example from MSDN: <xsd:schema xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:tns= "http://tempuri.org" targetNamespace= "http://tempuri.org" elementFormDefault= "qualified" > <xsd:element name= "PurchaseOrder" type= "tns:PurchaseOrderType" /> <xsd:complexType name= "PurchaseOrderType" > <xsd:sequence> <xsd:element name= "ShipTo" type= "tns:USAddress" maxOccurs= "2" /> <xsd:element name= "BillTo" type= "tns:USAddress" /> </xsd:

Append An Element To An Existing XML File (VB.NET)

Here's an example of appending a node to an xml file in VB.NET. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Dim doc As New XmlDocument() Dim file As New FileStream( "your_filename" , FileMode.Open) doc.Load(file) Try file.Close() file.Dispose() Dim root As XmlNode = doc.DocumentElement Dim el As XmlElement = doc.CreateElement( "Invoices" , "http://schemas.openxmlformats.org/package/2006/Invoices" ) el.SetAttribute( "Id" , "Test" ) doc.DocumentElement.AppendChild(el) root.InsertBefore(el, doc.DocumentElement.FirstChild) doc.Save( "your_filename" ) Catch ex As Exception Throw ex End Try Cheers!

Remove HTML Tags In An XML String Document Using Regular Expressions (REGEX) In C#

Here's a regex pattern that will match html tags that are present in an xml string document. Where xml, node1, node2, node3, node4, node5, node6 and node7 are xml tags. node1 could represent a valid xml tag name like employername or similar tag names. xmlStringData = Regex.Replace(xmlStringData, @"<((\??)|(/?)|(!))\s?\b(?! (\b(xml|node1||node2|node3|node4|node5|node6|node7)\b))\b[^>]*((/?))>" , " " , RegexOptions.IgnoreCase); Greg

Clean Invalid XML Characters In C#

Here's a cool way to clean Large XML files with invalid xml characters. Note: Stream from is the original xml file, while Stream to is the new xml file with invalid characters removed. private void Copy(Stream from , Stream to) { TextReader reader = new StreamReader( from ); TextWriter writer = new StreamWriter(to); writer.WriteLine(CleanInvalidXmlChars(reader.ReadToEnd())); writer.Flush(); } public static string CleanInvalidXmlChars( string text) { string re = @"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]" ; return Regex.Replace(text, re, "" ); } Source: http://social.msdn.microsoft.com/Forums/ Post: Invalid character returned from webservice

Read Or Parse XML Using XmlElement Class, XPath And XmlNodelist In C#

Sample xml file: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?xml version="1.0" encoding="UTF-8"?> <jobs> <job> <title> Payroll Analyst </title> <description> <summary> Seeking Payroll Analyst specialists. Great benefits and competitive salary. Must meet all requirements to be considered for assignment. </summary> </description> <location> <state> Pennsylvenia </state> </location> </job> <job /> </jobs> Code: 1 2 3 4 5 6 7 8 9 10 11 ListingSource = webclient.DownloadString( "your_xmlurl" ); StringReader readString = new System.IOStringReader(ListingSource); XmlDocument awesome = new XmlDocument(); awesome.Load(readString); XmlNodeList nodeList = awesome.SelectNodes( "//jobs/job" ); foreach (XmlElement element in nodeList) { title = elem

Invalid Expanded Name In LINQ to XML

Assuming I am reading this xml file using XLINQ. I encountered an error that says invalid expanded name. As i go through this xml file, i found a node images that contains element tags. The parent node is also an element tag. Since i don't use the images tag, I simply remove it using string manipulations. Below is the xml file and the solution: <element> <id> 2768687195 </id> <title> Customer Service Representative </title> <body> Do you dream of being your own boss and choosing the work you do, when you work and who you work for? </body> <url> http://jobs.myjob.careercenter-servicecrew.html </url> <category> <id> job/customer_service </id> <name> Customer Service &amp; Call Center Jobs </name> </category> <source> <id> www </id>

Donate