Thursday, July 30, 2009

Basic Funda of XML,XSD,XSLT

Suppose this is ur XML. Person.xml

<Persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Person>
<FirstName id="1">Kavita</FirstName>
<LastName>Khandhadia</LastName>
</Person>
<Person>
<FirstName id="2">Nishant</FirstName>
<LastName>Khandhadia</LastName>
</Person>
</Persons>

Now it may be possible that u want your XML to be in some proper format.. as XML is nothing but a
NODED string.. so you might want to validate your XML for following reasons

1 Wether it is in proper format or not
2 The node hierarchy is OK,or
3 If the data-types are correct in the XML

Now to validate an XML you must have something against which u can validate it..
We call it Schema file, which has normally XSD extensions.. there are other types of schema..but lets not get in to them right now..

Now for above example there can be an XSD file like this.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="Persons">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" ref="Person"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Person">
<xs:complexType>
<xs:sequence>
<xs:element ref="FirstName"/>
<xs:element ref="LastName"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="FirstName">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:NCName">
<xs:attribute name="id" use="required" type="xs:integer"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name="LastName" type="xs:NCName"/>
</xs:schema>



Basically the above XSD/Schema will define that the XML should have root element as Persons and it has to have child element named Person and so on.


Now you have to tell your XML that which XSD to be used.. For this you have to add this attribute to your XML file like this -

<Persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Documents%20and%20Settings/kavita.ACTLDOMAIN/Desktop/test/persons.xsd">

Now there are again ways to apply validations .. either using .net code behind or using some third party tool..

The code behind in C#.net to validate XML against XSD is as following.

public void ValidateXMLXSD()
{
string sFileName = Server.MapPath("person.xml");
XmlTextReader oTr = new XmlTextReader(sFileName);
XmlValidatingReader oVr = new XmlValidatingReader(oTr);

oVr.ValidationType = ValidationType.Schema;

oVr.ValidationEventHandler += new ValidationEventHandler(this.ValidationEvent);

while (oVr.Read())
{
if (oVr.NodeType == XmlNodeType.Text)
{
// lstXml.Items.Add(oVr.Value);
}
}

}

private void ValidationEvent(object s, ValidationEventArgs args)
{
Response.Write(args.Message.ToString());
//THe error messages will be print on screen.
}



Now lets come to XSLT...

Well it is one amazing way to transform one XML to another XML.
Suppose now in some case.. instead of above person.xml.. u want customer.xml which
takes data from person.xml but has totally different structure ..may be like this.


<?xml version='1.0' ?>
<Cusotmers>
<Customer>Kavita</Customer>
<Customer>Nishant</Customer>
</Cusotmers>


Following XSLT gives me output as above XML.

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

<xsl:template match="/">
<Cusotmers>
<xsl:for-each select="Persons/Person">
<Customer><xsl:value-of select="FirstName"/></Customer>
</xsl:for-each>
</Cusotmers>
</xsl:template>

</xsl:stylesheet>

Now again to transform the XML..and use XSLT the c#.net code behind is like this

XslTransform xslt = new XslTransform();
xslt.Load("file:///D:/Kavita/person.xslt");
//here sort.xslt shuid be the name of ur xslt file..please update the path also.
XPathDocument xpath = new XPathDocument("person.xml");
//here unSortXml is ur input XML.
Stream Streamdata = new FileStream(MapPath("Out.xml"), FileMode.Create, FileAccess.ReadWrite);
xslt.Transform(xpath, null, Streamdata, null);


FYI, u can write different types of transformation on single XML.

8 comments:

  1. Dear Kavita,

    This is indeed a good reference for a novice. Currently I am working on aassignment that requires an XML to be processed by an XSLT to output another XML.We have the XSD for the out put XML and transformation process (using XSLT)should take output XML XSD into consideration so that output XML is a validated one. Could you please help and provide your inputs on how to achieve this?
    My precise question is, How can we read/access an XSD into an XSLT so that we force transformed XML to adhere to the XSD?

    ReplyDelete
  2. Hi Kavita,

    I have a XML File and XSD File. But to convert the XML File to CSV Format I need the XSL format file.

    Is it possible to use the XSD file to generate the XSL Code.

    Rgds

    Sunil

    sunil_almnthat@yahoo.com

    ReplyDelete
  3. Dear Kavita,

    Thanks for the useful info. I believe a list of template codes and transformation rules can also be defined in DB tables (defining XPATH and Driver parameters) and a code in PL/SQL can be written around these tables to carry out XSLT Transformation of input XML which refers XSD schemalocation to validate the XML?

    Please let me know your views.

    Thanks once again.

    Saurabh

    ReplyDelete
  4. Hi Kavita,

    So far so good the below statement would generate error messages with respect to framework
    Response.Write(args.Message.ToString());

    for ex: if suryaprakasash.bg@gmail@.comm email is not valid in XML it would generate as The 'Email' element is invalid - invalid - The value 'suryaprakasash.bg@gmail@.comm' is invalid according to its datatype 'ValidateEmail' - The Pattern constraint failed.


    But I want error in XML as below
    Provided Email is Invalid ERREML007

    So help me in this regard

    ReplyDelete
  5. Good Work !!Kavita
    Keep posting

    ReplyDelete
  6. HI, Could you please help me on these xml things. Im new in these things. I have an xml file and I want to create a XSL-FO file so that I can create a pdf from it. I dont know how/where to start..
    omalbastin@gmail.com

    ReplyDelete
  7. how can i convert xml to xslt format. anywhere i can use tranformation xslt

    ReplyDelete
  8. Download the IBM M2150-810 Q&A PDF file easily to prepare IBM Security Web Fraud Sales Mastery Test v1 exam. It is particularly designed for IBM M2150-810 exam and our IBM specialists have created this M2150-810 Question Dumps observing the original M2150-810 exam.

    ReplyDelete