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.