Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

Sunday, January 20, 2013

Binding a XML DataSource to a TreeView

 
We have the below XMl file.

<?xml version="1.0"?>
<SuperProProductList>
<Product ID="1" Name="Chair">
<Price>49.33</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="2" Name="Car">
<Price>43399.55</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="3" Name="Fresh Fruit Basket">
<Price>49.99</Price>
<Available>False</Available>
<Status>4</Status>
</Product>
</SuperProProductList>

To bind the the above XML to a TreeView use the below code.

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="productListXML"
AutoGenerateDataBindings="False">
<DataBindings>
<asp:TreeNodeBinding DataMember="SuperProProductList" Text="Product List" />
<asp:TreeNodeBinding DataMember="Available" TextField="#InnerText" />
<asp:TreeNodeBinding DataMember="Product" TextField="Name" />
<asp:TreeNodeBinding DataMember="Price" TextField="#InnerText" />
</DataBindings>
</asp:TreeView>

<asp:XmlDataSource ID="productListXML" runat="server"
DataFile="~/productListXML.xml"></asp:XmlDataSource>

Output:

The Xml Web Control in ASP.NET

 
ASP.NET includes an Xml web control that fills the gap and can display XML content. You can specify the XML content for this control in several ways: by assigning an XmlDocument object to the Document property, by assigning a string containing the XML content to the DocumentContent property, or by specifying a string that refers to an XML file using the DocumentSource property.

// Display the information from an XML file in the Xml control.
Xml.DocumentSource = Path.Combine(Request.PhysicalApplicationPath,
@"App_Data\SuperProProductList.xml");

//XML File
<?xml version="1.0"?>
<SuperProProductList>
<Product ID="1" Name="Chair">
<Price>49.33</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="2" Name="Car">
<Price>43399.55</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="3" Name="Fresh Fruit Basket">
<Price>49.99</Price>
<Available>False</Available>
<Status>4</Status>
</Product>
</SuperProProductList>

If you assign the SuperProProductList.xml file to the Xml control, you’re likely to be disappointed. The result is just a string of the inner text (the price for each product), bunched together without a space (see Figure 1).

Figure 1


However, you can also apply an XSLT style sheet, either by assigning an XslCompiledTransform object to the Transform property or by using a string that refers to the XSLT file with the TransformSource property:

//XSLT sheet(Style sheet)
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0" >
<xsl:template match="SuperProProductList">
<html>
<body>
<table border="1">
<xsl:apply-templates select="Product"/>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="Product">
<tr>
<td><xsl:value-of select="@ID"/></td>
<td><xsl:value-of select="@Name"/></td>
<td><xsl:value-of select="Price"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>

// Specify a XSLT file.
Xml.TransformSource = Path.Combine(Request.PhysicalApplicationPath,
@"App_Data\SuperProProductList.xslt")

Now the output is automatically formatted according to your style sheet (see Figure 2).

Figure 2



Saturday, January 19, 2013

XML attributes

 
Attributes add extra information to an element. Instead of putting information into a subelement, you can use an attribute. In the XML community, deciding whether to use subelements or attributes—and what information should go into an attribute—is a matter of great debate, with no clear consensus. Here’s the SuperProProductList example with ID and Name attributes instead of ID and Name subelements:

<?xml version="1.0"?>
<SuperProProductList>
<Product ID="1" Name="Chair">
<Price>49.33</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="2" Name="Car">
<Price>43399.55</Price>
<Available>True</Available>
<Status>3</Status>
</Product>
<Product ID="3" Name="Fresh Fruit Basket">
<Price>49.99</Price>
<Available>False</Available>
<Status>4</Status>
</Product>
</SuperProProductList>

Using attributes in XML is more stringent than in HTML. In XML, attributes must always have values, and these values must use quotation marks. For example, <ProductName="Chair" /> is acceptable, but <Product Name=Chair /> or <Product Name /> isn’t. However, you do have one bit of flexibility—you can use single or double quotes around any attribute value. It’s convenient to use single quotes if you know the text value inside will contain a double quote (as in <Product Name='Red "Sizzle" Chair' />). If your text value has both single and double quotes, use double quotes around the value and replace the double quotes inside the value with the &quot; entity equivalent.

XML Basics

 
Part of XML’s popularity is a result of its simplicity. When creating your own XML document, you need to remember only a few rules:

• XML elements are composed of a start tag (like <Name>) and an end tag (like </Name>). Content is placed between the start and end tags. If you include a start tag, you must also include a corresponding end tag. The only other option is to combine the two by creating an empty element, which includes a forward slash at the end and has no content (like <Name />). This is similar to the syntax for ASP.NET controls.

• Whitespace between elements is ignored. That means you can freely use tabs and hard returns to properly align your information.

• You can use only valid characters in the content for an element. You can’t enter special characters, such as the angle brackets (< >) and the ampersand (&), as content. Instead, you’ll have to use the entity equivalents (such as &lt; and &gt; for angle brackets, and &amp; for the ampersand). These equivalents will be automatically converted to the original characters when you read them into your program with the appropriate .NET classes.

• XML elements are case sensitive, so <ID> and <id> are completely different elements. 

• All elements must be nested in a root element. In the SuperProProductList example, the root element is <SuperProProductList>. As soon as the root element is closed, the document is finished, and you cannot add anything else after it. In other words, if you omit the <SuperProProductList> element and start with a <Product> element, you’ll be able to enter information for only one product; this is because as soon as you add the closing </Product>, the document is complete. (HTML has a similar rule and requires that all page content be nested in a root <html> element, but most browsers let you get away without following this rule.)

• Every element must be fully enclosed. In other words, when you open a subelement, you need to close it before you can close the parent. <Product><ID></ID></Product> is valid, but <Product><ID></Product></ID> isn’t. As a general rule, indent when you open a new element, because this will allow you to see the document’s structure and notice if you accidentally close the wrong element first.

• XML documents must start with an XML declaration like <?xml version="1.0"?>. This signals that the document contains XML and indicates any special text encoding. However, many XML parsers work fine even if this detail is omitted. As long as you meet these requirements, your XML document can be parsed and displayed as a basic tree. This means your document is well formed, but it doesn’t mean it is valid. For example, you may still have your elements in the wrong order (for example, <ID><Product></Product></ID>), or you may have the wrong type of data in a given field (for example, <ID>Chair</ID><Name>2</Name>). You can impose these additional rules on your XML documents, as you’ll see later in this chapter when you consider XML schemas. Elements are the primary units for organizing information in XML (as demonstrated with the SuperProProductList example), but they aren’t the only option. You can also use attributes.

Tuesday, December 25, 2012

Write to a XML File in C#.NET

 
Below program will allow you to write XML text into a stream and then save it into an xml file.

private void WriteToXML()
    {
        XmlWriterSettings settings = new XmlWriterSettings(); 
        settings.Indent = true; 
        XmlWriter writer = XmlWriter.Create(Server.MapPath("Products.xml"), settings); 
        writer.WriteStartDocument(); 
        writer.WriteComment("This is a generated XML File."); 
        writer.WriteStartElement("Product"); 
        writer.WriteAttributeString("ID", "001"); 
        writer.WriteAttributeString("Name", "Soap"); 
        writer.WriteElementString("Price", "10.00"); 
        writer.WriteStartElement("ProductDetails"); 
        writer.WriteElementString("BrandName", "A Soap"); 
        writer.WriteElementString("Manufacturer", "AB Company"); 
        writer.WriteEndElement(); 
        writer.WriteEndDocument(); 
        writer.Flush(); 
        writer.Close();
    }

Output:

<?xml version="1.0" encoding="utf-8" ?>
- <!-- This file is generated by the program.
-->
<Product ID="001" Name="Soap">
  <Price>10.00</Price>
<OtherDetails>
   <BrandName>X Soap</BrandName>
   <Manufacturer>X Company</Manufacturer>
</OtherDetails>
</Product>

writer.WriteStartDocument()
Write the XML declaration. You can find on top of the XML document.

writer.WriteComment()
Write the XML comment.

writer.WriteStartElement()
Write the element of the XML.

writer.WriteAttributeString()
Add attributes to a element.

writer.WriteEndElement()
Closes the element.

writer.WriteEndDocument()
End writing the XML document.

Finally, we used the XmlWriter.Flush() method to clean the contents of the stream and the XmlWriter.Close() method to save the file and stop the program from using it

Friday, December 14, 2012

Comma Separated string in Sql Server using XPATH

 
We have the below table.

number
2
10


Expected out put:

ItemList
2, 10

We can use XML Xpath expression in our select query to get the above result.

select ItemList = substring((select(', '+CONVERT(varchar,number)) from tbltest
FOR XML PATH( '' )),2,100)

substring()
Expects three parameters
SUBSTRING ( expression ,start , length )

expression
Is a character, binary, text, ntext, or image expression.

start
Is an integer or bigint expression that specifies where the returned characters start.

length
Is a positive integer or bigint expression that specifies how many characters of the expression will be returned.

FOR XML PATH
TYPE to create a typed XML value (as opposed to a string containing xml). An XML typed subquery will create an XML element, a string will just insert the result as text() and will be escaped.

XML Parsing in ASP.NET

 
Using the System.Xml name space we can parse and XML file to read the parent node, Child node and the attributes.

In below example Students is the parent node and Student is the child node. ID, Name, Address, City and STID are attributes.

private void ParsingXMLFile()

{
   string myXMl = "<Students>" +
                 "<Student ID='1' Name='Chamara' " +
                      "Address='305 Kandy' " +
                      "City='Kandy' STID='1005'> " +
                 "</Student>" +
               "</Students>";

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(myXMl);

        XmlNodeList xNodeList = xDoc.SelectNodes("Students/child::node()");
        foreach (XmlNode xNode in xNodeList)
        {
            if (xNode.Name == "Student")
            {
                string ID = xNode.Attributes["ID"].Value;
                Response.Write(ID + "<br/>");
                string Name = xNode.Attributes["Name"].Value;
                Response.Write(Name + "<br/>");
                string Address = xNode.Attributes["Address"].Value;
                Response.Write(Address + "<br/>");
                string City = xNode.Attributes["City"].Value;
                Response.Write(City + "<br/>");
                string STID = xNode.Attributes["STID"].Value;
                Response.Write(STID + "<br/>");
            }
        }
    }

Out put:
1
Chamara
305 Kandy
Kandy
1005

Friday, December 7, 2012

Read XML File in C#.NET

 
First create your XML file.

<?xml version="1.0" encoding="utf-8" ?>
<customers>
  <customer age="19" gender="female">
    <name>Kevin Anders</name>
    <phone>555.555.5555</phone>
  </customer>
  <customer age="22" gender="male">
    <name>Staci Richard</name>
    <phone>555.122.1552</phone>
  </customer>
</customers>

customers - Root element
customer - Node element
age, gender - Node attributes
name, phone - TextNode

Below method will read the XML documents each attribute and the elements.

 private void readXMLNodes()
    {
        //Create XML document object
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/XMLFile.xml"));
        //get the node list
        XmlNodeList customers = doc.SelectNodes("//customer");

        foreach (XmlNode customer in customers)
        {
            //Display the text in each element.
            Response.Write("Name: " + customer["name"].InnerText +" - "+"Phone: "+customer["phone"].InnerText);
            Response.Write("<br/>");
            //Display the text in each attribute.
            Response.Write("Gender: "+customer.Attributes["gender"].Value.ToString());
            Response.Write("<br/>");
            Response.Write("Age: "+customer.Attributes["age"].Value.ToString());
            Response.Write("<br/>");
            Response.Write("<br/>");
          
        }
    }

Out put:
Name: Kevin Anders - Phone: 555.555.5555
Gender: female
Age: 19

Name: Staci Richard - Phone: 555.122.1552
Gender: male
Age: 22

Sunday, December 2, 2012

XML and Related Technologies: DTD - Document Type Definition

 
DTD - Document Type Definition
A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes.
A DTD can be declared inline inside an XML document, or as an external reference.

What Does the DOCTYPE Declaration (DTD) Do?
The DOCTYPE Declaration (DTD or Document Type Declaration) does a couple of things:
  1. When performing HTML validation testing on a web page it tells the HTML (HyperText Markup Language) validator which version of (X)HTML standard the web page coding is supposed to comply with. When you validate your web page the HTML validator checks the coding against the applicable standard then reports which portions of the coding do not pass HTML validation (are not compliant).
  2. It tells the browser how to render the page in standards compliant mode.
So basically what DTD does is validating a XML document.

Internal DTD Declaration
If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the
following syntax:
<!DOCTYPE root-element [element-declarations]>

Example XML document with an internal DTD:
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>


The DTD in the above Tasks is interpreted like as below:
• !DOCTYPE note defines that the root element of this document is note
• !ELEMENT note defines that the note element contains four elements: "to,from,heading,body"
• !ELEMENT to defines the to element to be of type "#PCDATA"
• !ELEMENT from defines the from element to be of type "#PCDATA"
• !ELEMENT heading defines the heading element to be of type "#PCDATA"
• !ELEMENT body defines the body element to be of type "#PCDATA"

External DTD Declaration

If the DTD is declared in an external file, it should be wrapped in a DOCTYPE definition with the following
syntax:
<!DOCTYPE root-element SYSTEM "filename">

External DTD Declaration Example
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

And this is the file "note.dtd" which contains the DTD:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>