SlideShare a Scribd company logo
Mohammad Shaker 
mohammadshaker.com 
@ZGTRShaker 
2011, 2012, 2013, 2014 
C# Advanced 
L03-XML & LINQ TO XML
XML
XML –The Definition
XML 
•HTML and XHTML? 
•XML 
–Extensible Markup Language 
–A metalanguagethat allows users to define their own customized markup languages, especially in order to display documents on the World Wide Web (WWW). 
•XSD 
–XML Schema Definition language 
•XDR 
–XML -Data Reduced schemas. 
•Tags
XML 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts>
XML 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts>
XML 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts> 
Contacts
XML 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts> 
Contacts
XML 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts> 
Contacts 
Contact 
Contact
XML 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts> 
Contacts 
Mohammad 
Shaker 
Hamza 
Smith
XML .NET Classes 
Class 
Description 
XmlNode 
Represents a single node in a document tree. It is the base of many of the 
classes shown in this chapter. If this node represents the root of an XML 
document, you can navigate to any position in the document from it. 
XmlDocument 
Extends the XmlNodeclass, but is often the first object you use when using 
XML. That’s because this class is used to load and save data from disk or 
elsewhere.
XML .NET Classes 
Class 
Description 
XmlElement 
Represents a single element in the XML document. XmlElementis derived 
from XmlLinkedNode, which in turn is derived from XmlNode. 
XmlAttribute 
Represents a single attribute. Like the XmlDocumentclass, it is derived from 
the XmlNodeclass. 
XmlText 
Represents the text between a starting tag and a closing tag. 
XmlComment 
Represents a special kind of node that is not regarded as part of the document 
other than to provide information to the reader about parts of the document. 
XmlNodeList 
Represents a collection of nodes.
Creating an XML Node in an XML FileProgrammatically
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Create an XML File 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Create an XML Node 
users 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Append the XML Node to the XML File 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Create an XML Node 
user 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Append the node: user to the root node: users 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Create another XML Node user 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Creating XML Node 
static void Main(string[] args) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
XmlNoderootNode= xmlDoc.CreateElement("users"); 
xmlDoc.AppendChild(rootNode); 
XmlNodeuserNode= xmlDoc.CreateElement("user"); 
XmlAttributeattribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "42"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "John Doe"; 
rootNode.AppendChild(userNode); 
userNode= xmlDoc.CreateElement("user"); 
attribute = xmlDoc.CreateAttribute("age"); 
attribute.Value= "39"; 
userNode.Attributes.Append(attribute); 
userNode.InnerText= "Jane Doe"; 
rootNode.AppendChild(userNode); 
xmlDoc.Save("test-doc.xml"); 
} 
Save the file where you want 
<users> 
<user age="42">John Doe</user> 
<user age="39">Jane Doe</user> 
</users>
Building a Node -A Faster Way? 
XElementxml=newXElement("contacts", 
newXElement("contact", 
newXAttribute("contactId", "2"), 
newXElement("firstName", "Mohammad"), 
newXElement("lastName", "Shaker") 
), 
newXElement("contact", 
newXAttribute("contactId", "3"), 
newXElement("firstName", "Hamza"), 
newXElement("lastName", "Smith") 
) 
); 
Console.WriteLine(xml);
Building a Node -A Faster Way? 
XElementxml=newXElement("contacts", 
newXElement("contact", 
newXAttribute("contactId", "2"), 
newXElement("firstName", "Mohammad"), 
newXElement("lastName", "Shaker") 
), 
newXElement("contact", 
newXAttribute("contactId", "3"), 
newXElement("firstName", "Hamza"), 
newXElement("lastName", "Smith") 
) 
); 
Console.WriteLine(xml); 
<contacts> 
<contactcontactId="2"> 
<firstName>Mohammad</firstName> 
<lastName>Shaker</lastName> 
</contact> 
<contactcontactId="3"> 
<firstName>Hamza</firstName> 
<lastName>Smith</lastName> 
</contact> 
</contacts>
Searching an XML
XML 
•Selecting Nodes
XML 
•Selecting Nodes
XML 
•Selecting Nodes
Getting XML Node Values
XML 
<?xml version="1.0" encoding="utf-8"?> 
<RoomsCoordProperties> 
<LocationDimension> 10 </LocationDimension> 
<Number> 5 </Number> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
<BasicLocationLength> 4 </BasicLocationLength> 
<Room id="3"> 
<LocationID> 0 </LocationID> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
</Room> 
… 
public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
xmlDoc.Load(XMLFilePath); 
XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); 
myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); 
myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); 
myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); 
myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); 
myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); 
myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); 
}
XML 
<?xml version="1.0" encoding="utf-8"?> 
<RoomsCoordProperties> 
<LocationDimension> 10 </LocationDimension> 
<Number> 5 </Number> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
<BasicLocationLength> 4 </BasicLocationLength> 
<Room id="3"> 
<LocationID> 0 </LocationID> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
</Room> 
… 
public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
xmlDoc.Load(XMLFilePath); 
XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); 
myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); 
myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); 
myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); 
myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); 
myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); 
myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); 
}
XML 
<?xml version="1.0" encoding="utf-8"?> 
<RoomsCoordProperties> 
<LocationDimension> 10 </LocationDimension> 
<Number> 5 </Number> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
<BasicLocationLength> 4 </BasicLocationLength> 
<Room id="3"> 
<LocationID> 0 </LocationID> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
</Room> 
… 
public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
xmlDoc.Load(XMLFilePath); 
XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); 
myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); 
myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); 
myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); 
myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); 
myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); 
myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); 
}
XML 
<?xml version="1.0" encoding="utf-8"?> 
<RoomsCoordProperties> 
<LocationDimension> 10 </LocationDimension> 
<Number> 5 </Number> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
<BasicLocationLength> 4 </BasicLocationLength> 
<Room id="3"> 
<LocationID> 0 </LocationID> 
<Width> 12 </Width> 
<Length> 12 </Length> 
<Height> 3 </Height> 
<Opacity> 0.3 </Opacity> 
</Room> 
… 
public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) 
{ 
XmlDocumentxmlDoc= new XmlDocument(); 
xmlDoc.Load(XMLFilePath); 
XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); 
myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); 
myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); 
myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); 
myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); 
myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); 
myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); 
}
LINQ to XMLXML to LINQ
LINQ and XML 
•LINQ to XML 
•XML to LINQ 
varquery = from p in people 
where p.CanCode 
select new Xelement(“Person”, new Xattribute(“Age”, p.Age), p.Name) 
varx = new XElement(“People”, 
from p in people 
where p.CanCode 
select new Xelement(“Person”, new Xattribute(“Age”, p.Age), p.Name) 
)
LINQ to XML 
•Let’s have the following XML file 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
LINQ to XML 
XmlNodesearched=null; 
XmlDocumentdoc=newXmlDocument(); 
doc.Load(@"D:Temporarycustomers.xml"); 
foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) 
{ 
if(node.Attributes["id"].InnerText=="80") 
{ 
searched=node; 
break; 
} 
}
LINQ to XML 
XmlNodesearched=null; 
XmlDocumentdoc=newXmlDocument(); 
doc.Load(@"D:Temporarycustomers.xml"); 
foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) 
{ 
if(node.Attributes["id"].InnerText=="80") 
{ 
searched=node; 
break; 
} 
} 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Attribute("id") =="80" 
selectc;
LINQ to XML 
XmlNodesearched=null; 
XmlDocumentdoc=newXmlDocument(); 
doc.Load(@"D:Temporarycustomers.xml"); 
foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) 
{ 
if(node.Attributes["id"].InnerText=="80") 
{ 
searched=node; 
break; 
} 
} 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Attribute("id") =="80" 
selectc; 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
LINQ to XML 
XmlNodesearched=null; 
XmlDocumentdoc=newXmlDocument(); 
doc.Load(@"D:Temporarycustomers.xml"); 
foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) 
{ 
if(node.Attributes["id"].InnerText=="80") 
{ 
searched=node; 
break; 
} 
} 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Attribute("id") =="80" 
selectc; 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
LINQ to XML 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Element("name").Attribute("value") =="Sample Name" 
selectc; 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
LINQ to XML 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Element("name").Attribute("value") =="Sample Name" 
selectc; 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
LINQ to XML 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Attribute("id") =="84" 
&&(string)c.Element("name").Attribute("value") =="Sample Name" 
selectc; 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
LINQ to XML 
XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); 
IEnumerable<XElement>searched= 
fromcinmain.Elements("customer") 
where(string)c.Attribute("id") =="84" 
&&(string)c.Element("name").Attribute("value") =="Sample Name" 
selectc; 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customers> 
<customerid="84"> 
<namevalue="Sample Name"/> 
</customer> 
<customerid="89"> 
<namevalue="Sample Name 2"/> 
</customer> 
<customerid="80"> 
<namevalue="Sample Name 3"/> 
</customer> 
</customers>
Performanceof LINQ 
•LINQ has more control and efficiency in O/R Mapping than NHibernate 
–LINQ: ExternlMapping or Attribute Mapping 
–NHibernate: ExternlMapping 
•Because of mapping, LINQ is lower than database tools such as SqlDataReaderor SqlDataAdapter 
–In large dataset, their performance are more and more similar
XML Serialization
XML SerializationNot Always an Easy, Straightforward Task
XML SerializationWhy to?
XML SerializationSerialize a class that simply consists of public fields and properties into an XML file
XML SerializationUse XML serialization to generate an XML stream that conforms to a specific XML Schema (XSD) document.
Test CaseSerializing a Class
XML Serialization 
namespace XMLTest1 
{ 
public class Test 
{ 
public String value1; 
public String value2; 
} 
class Program 
{ 
static void Main(string[] args) 
{ 
Test myTest= new Test() { value1 = "Value 1", value2 = "Value 2" }; 
XmlSerializerx = new XmlSerializer(myTest.GetType()); 
x.Serialize(Console.Out, myTest); 
Console.ReadKey(); 
} 
} 
}
XML Serialization 
namespace XMLTest1 
{ 
public class Test 
{ 
public String value1; 
public String value2; 
} 
class Program 
{ 
static void Main(string[] args) 
{ 
Test myTest= new Test() { value1 = "Value 1", value2 = "Value 2" }; 
XmlSerializerx = new XmlSerializer(myTest.GetType()); 
x.Serialize(Console.Out, myTest); 
Console.ReadKey(); 
} 
} 
} 
<?xml version="1.0" encoding="ibm850"?> 
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<value1>Value 1</value1> 
<value2>Value 2</value2> 
</Test> 
That’s Cool!
Test CaseDeSerializinga Class
XML DeSerialization 
namespace XMLTest1 
{ 
public class Test 
{ 
public String value1; 
public String value2; 
} 
class Program 
{ 
static void Main(string[] args) 
{ 
String xData= "<?xml version="1.0" encoding="ibm850"?><Test xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><value1>Value 1</value1><value2>Value 2</value2></Test>"; 
XmlSerializerx = new XmlSerializer(typeof(Test)); 
Test myTest= (Test)x.Deserialize(new StringReader(xData)); 
Console.WriteLine("V1: " + myTest.value1); 
Console.WriteLine("V2: " + myTest.value2); 
Console.ReadKey(); 
} 
} 
}
XML DeSerialization 
namespace XMLTest1 
{ 
public class Test 
{ 
public String value1; 
public String value2; 
} 
class Program 
{ 
static void Main(string[] args) 
{ 
String xData= "<?xml version="1.0" encoding="ibm850"?><Test xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><value1>Value 1</value1><value2>Value 2</value2></Test>"; 
XmlSerializerx = new XmlSerializer(typeof(Test)); 
Test myTest= (Test)x.Deserialize(new StringReader(xData)); 
Console.WriteLine("V1: " + myTest.value1); 
Console.WriteLine("V2: " + myTest.value2); 
Console.ReadKey(); 
} 
} 
}
XML Serialization and Attributes
XML Serialization and Attributes 
[XmlRoot("XTest")] 
public class Test 
{ 
[XmlElement(ElementName="V1")] 
public String value1; 
[XmlElement(ElementName="V2")] 
public String value2; 
[XmlArray("OtherValues")] 
[XmlArrayItem("OValue")] 
public List others = new List(); 
}
XML Serialization and Attributes 
[XmlRoot("XTest")] 
public class Test 
{ 
[XmlElement(ElementName="V1")] 
public String value1; 
[XmlElement(ElementName="V2")] 
public String value2; 
[XmlArray("OtherValues")] 
[XmlArrayItem("OValue")] 
public List others = new List(); 
} 
<?xml version="1.0" encoding="ibm850"?> 
<XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<V1>A1</V1> 
<V2>B1</V2> 
<OtherValues> 
<OValue>Test</OValue> 
</OtherValues> 
</XTest>
XML Serialization and Attributes 
[XmlRoot("XTest")] 
public class Test 
{ 
[XmlElement(ElementName="V1")] 
public String value1; 
[XmlElement(ElementName="V2")] 
public String value2; 
[XmlArray("OtherValues")] 
[XmlArrayItem("OValue")] 
public List others = new List(); 
} 
<?xml version="1.0" encoding="ibm850"?> 
<XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<V1>A1</V1> 
<V2>B1</V2> 
<OtherValues> 
<OValue>Test</OValue> 
</OtherValues> 
</XTest>
XML Serialization and Attributes 
[XmlRoot("XTest")] 
public class Test 
{ 
[XmlElement(ElementName="V1")] 
public String value1; 
[XmlElement(ElementName="V2")] 
public String value2; 
[XmlArray("OtherValues")] 
[XmlArrayItem("OValue")] 
public List others = new List(); 
} 
<?xml version="1.0" encoding="ibm850"?> 
<XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<V1>A1</V1> 
<V2>B1</V2> 
<OtherValues> 
<OValue>Test</OValue> 
</OtherValues> 
</XTest>
XML Serialization and Attributes 
[XmlRoot("XTest")] 
public class Test 
{ 
[XmlElement(ElementName="V1")] 
public String value1; 
[XmlElement(ElementName="V2")] 
public String value2; 
[XmlArray("OtherValues")] 
[XmlArrayItem("OValue")] 
public List others = new List(); 
} 
<?xml version="1.0" encoding="ibm850"?> 
<XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<V1>A1</V1> 
<V2>B1</V2> 
<OtherValues> 
<OValue>Test</OValue> 
</OtherValues> 
</XTest>
XML Serialization and Attributes 
[XmlRoot("XTest")] 
public class Test 
{ 
[XmlElement(ElementName="V1")] 
public String value1; 
[XmlElement(ElementName="V2")] 
public String value2; 
[XmlArray("OtherValues")] 
[XmlArrayItem("OValue")] 
public List others = new List(); 
} 
<?xml version="1.0" encoding="ibm850"?> 
<XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<V1>A1</V1> 
<V2>B1</V2> 
<OtherValues> 
<OValue>Test</OValue> 
</OtherValues> 
</XTest>
XML Documentation
XML DocumentationC# provides a mechanism for developers to document their code using XML. In source code files, lines that begin with ///and that precede a user-defined type such as a class, delegate, or interface; a member such as a field, event, property, or method; or a namespace declaration can be processed as comments and placed in a file.
XML Documentation 
/// <summary> 
/// Class level summary documentation goes here.</summary> 
/// <remarks> 
/// Longer comments can be associated with a type or member 
/// through the remarks tag</remarks> 
public class SomeClass 
{ 
/// <summary> 
/// Store for the name property</summary> 
private string myName= null; 
/// <summary> 
/// The class constructor. </summary> 
public SomeClass() 
{ 
// TODO: Add Constructor Logic here 
} 
/// <summary> 
/// Name property </summary> 
/// <value> 
/// A value tag is used to describe the property value</value> 
public string Name 
{ 
get 
{ 
return myName; 
} 
} 
/// <summary> 
/// Description for SomeMethod.</summary> 
/// <paramname="s"> Parameter description for s goes here</param> 
/// <seealsocref="String"> 
/// You can use the crefattribute on any tag to reference a type or member 
/// and the compiler will check that the reference exists. </seealso> 
public void SomeMethod(string s) { }
XML Documentation 
/// <summary> 
/// Class level summary documentation goes here.</summary> 
/// <remarks> 
/// Longer comments can be associated with a type or member 
/// through the remarks tag</remarks> 
public class SomeClass 
{ 
/// <summary> 
/// Store for the name property</summary> 
private string myName= null; 
/// <summary> 
/// The class constructor. </summary> 
public SomeClass() 
{ 
// TODO: Add Constructor Logic here 
} 
/// <summary> 
/// Name property </summary> 
/// <value> 
/// A value tag is used to describe the property value</value> 
public string Name 
{ 
get 
{ 
return myName; 
} 
} 
/// <summary> 
/// Description for SomeMethod.</summary> 
/// <paramname="s"> Parameter description for s goes here</param> 
/// <seealsocref="String"> 
/// You can use the crefattribute on any tag to reference a type or member 
/// and the compiler will check that the reference exists. </seealso> 
public void SomeMethod(string s) { }
XML Documentation 
/// <summary> 
/// Class level summary documentation goes here.</summary> 
/// <remarks> 
/// Longer comments can be associated with a type or member 
/// through the remarks tag</remarks> 
public class SomeClass 
{ 
/// <summary> 
/// Store for the name property</summary> 
private string myName= null; 
/// <summary> 
/// The class constructor. </summary> 
public SomeClass() 
{ 
// TODO: Add Constructor Logic here 
} 
/// <summary> 
/// Name property </summary> 
/// <value> 
/// A value tag is used to describe the property value</value> 
public string Name 
{ 
get 
{ 
return myName; 
} 
} 
/// <summary> 
/// Description for SomeMethod.</summary> 
/// <paramname="s"> Parameter description for s goes here</param> 
/// <seealsocref="String"> 
/// You can use the crefattribute on any tag to reference a type or member 
/// and the compiler will check that the reference exists. </seealso> 
public void SomeMethod(string s) { } 
<?xml version="1.0"?> 
<doc> 
<assembly> 
<name>xmlsample</name> 
</assembly> 
<members> 
<member name="T:SomeClass"> 
<summary> 
Class level summary documentation goes here. 
</summary> 
<remarks> 
Longer comments can be associated with a type or member 
through the remarks tag 
</remarks> 
</member> 
<member name="F:SomeClass.myName"> 
<summary> 
Store for the name property 
</summary> 
</member> 
<member name="M:SomeClass.#ctor"> 
<summary>The class constructor.</summary> 
</member> 
<member name="M:SomeClass.SomeMethod(System.String)"> 
<summary>Description for SomeMethod.</summary> 
<paramname="s"> Parameter description for s goes here</param> 
<seealsocref="T:System.String"> 
You can use the crefattribute on any tag to reference a type or member 
and the compiler will check that the reference exists. </seealso> 
</member> 
…. 
</doc>
XML Documentation 
/// <summary> 
/// Class level summary documentation goes here.</summary> 
/// <remarks> 
/// Longer comments can be associated with a type or member 
/// through the remarks tag</remarks> 
public class SomeClass 
{ 
/// <summary> 
/// Store for the name property</summary> 
private string myName= null; 
/// <summary> 
/// The class constructor. </summary> 
public SomeClass() 
{ 
// TODO: Add Constructor Logic here 
} 
/// <summary> 
/// Name property </summary> 
/// <value> 
/// A value tag is used to describe the property value</value> 
public string Name 
{ 
get 
{ 
return myName; 
} 
} 
/// <summary> 
/// Description for SomeMethod.</summary> 
/// <paramname="s"> Parameter description for s goes here</param> 
/// <seealsocref="String"> 
/// You can use the crefattribute on any tag to reference a type or member 
/// and the compiler will check that the reference exists. </seealso> 
public void SomeMethod(string s) { } 
<?xml version="1.0"?> 
<doc> 
<assembly> 
<name>xmlsample</name> 
</assembly> 
<members> 
<member name="T:SomeClass"> 
<summary> 
Class level summary documentation goes here. 
</summary> 
<remarks> 
Longer comments can be associated with a type or member 
through the remarks tag 
</remarks> 
</member> 
<member name="F:SomeClass.myName"> 
<summary> 
Store for the name property 
</summary> 
</member> 
<member name="M:SomeClass.#ctor"> 
<summary>The class constructor.</summary> 
</member> 
<member name="M:SomeClass.SomeMethod(System.String)"> 
<summary>Description for SomeMethod.</summary> 
<paramname="s"> Parameter description for s goes here</param> 
<seealsocref="T:System.String"> 
You can use the crefattribute on any tag to reference a type or member 
and the compiler will check that the reference exists. </seealso> 
</member> 
…. 
</doc>
XML Documentation 
•To build the XML Documentation sample 
–To generate the sample XML documentation, type the following at the command prompt: 
•cscXMLsample.cs/doc:XMLsample.xml 
–To see the generated XML, issue the following command: 
•type XMLsample.xml

More Related Content

PDF
CSharp Advanced L05-Attributes+Reflection
PDF
C# Advanced L07-Design Patterns
PDF
Designing a JavaFX Mobile application
PDF
Rich Internet Applications con JavaFX e NetBeans
PPTX
JavaScript Fundamentals & JQuery
PPTX
Javascript best practices
KEY
Xtext Eclipse Con
PPTX
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
CSharp Advanced L05-Attributes+Reflection
C# Advanced L07-Design Patterns
Designing a JavaFX Mobile application
Rich Internet Applications con JavaFX e NetBeans
JavaScript Fundamentals & JQuery
Javascript best practices
Xtext Eclipse Con
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...

What's hot (20)

PPTX
Javascript 101
PPT
Learn javascript easy steps
PPTX
An Introduction to JavaScript
PDF
Javascript Best Practices
PPTX
Java script basics
PPT
Intro To Hibernate
PDF
Patterns for JVM languages - Geecon 2014
PPT
Java script -23jan2015
PDF
Secrets of JavaScript Libraries
PPTX
PDF
JavaScript - Chapter 8 - Objects
KEY
PPTX
Lab#1 - Front End Development
PPTX
Java script
PPS
Ado.net session11
PPT
Hibernate
ODP
Scala Reflection & Runtime MetaProgramming
PPTX
Java script
PPT
Javascript 101
Learn javascript easy steps
An Introduction to JavaScript
Javascript Best Practices
Java script basics
Intro To Hibernate
Patterns for JVM languages - Geecon 2014
Java script -23jan2015
Secrets of JavaScript Libraries
JavaScript - Chapter 8 - Objects
Lab#1 - Front End Development
Java script
Ado.net session11
Hibernate
Scala Reflection & Runtime MetaProgramming
Java script
Ad

Viewers also liked (20)

PDF
Procesamiento de XML en C#
PPTX
XML en .NET
PDF
Asynchronous programming in .net 4.5 with c#
PPT
.Net 3.5
PPT
Advanced c#
PDF
27418524 design-patterns-dot-net-with-examples
PPTX
.NET 4.0 Code Contracts (2010)
PPTX
Microsoft Managed Extensibility Framework
PPTX
Advanced C#. Part 2
PPTX
Advanced C#. Part 1
ZIP
.Net 4.0 Threading and Parallel Programming
PPT
Cloud Computing
PPTX
What’s new in Visual Studio 2012 & .NET 4.5
PDF
Patterns For Cloud Computing
PPTX
Cloud Computing
PPT
SOA Unit I
PPT
Web Application Development Fundamentals
PPTX
Introduction to xml
PPT
Introduction to XML
PPT
Design Patterns (Examples in .NET)
Procesamiento de XML en C#
XML en .NET
Asynchronous programming in .net 4.5 with c#
.Net 3.5
Advanced c#
27418524 design-patterns-dot-net-with-examples
.NET 4.0 Code Contracts (2010)
Microsoft Managed Extensibility Framework
Advanced C#. Part 2
Advanced C#. Part 1
.Net 4.0 Threading and Parallel Programming
Cloud Computing
What’s new in Visual Studio 2012 & .NET 4.5
Patterns For Cloud Computing
Cloud Computing
SOA Unit I
Web Application Development Fundamentals
Introduction to xml
Introduction to XML
Design Patterns (Examples in .NET)
Ad

Similar to C# Advanced L03-XML+LINQ to XML (20)

PPTX
PPTX
java API for XML DOM
PPT
Understanding XML DOM
PPTX
Simple xml in .net
PPTX
Part 7
PPTX
The xml
PPT
XMLLec1.pptsfsfsafasfasdfasfdsadfdsfdf dfdsfds
PPT
XMLLec1 (1xML lecturefsfsdfsdfdsfdsfsdfsdfdsf
PPT
XML stands for EXtensible Markup Language
PPTX
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
PDF
Jdom how it works & how it opened the java process
PDF
Advanced Web Programming Chapter 12
PPTX
Xsd restrictions, xsl elements, dhtml
PDF
Xml And JSON Java
PPTX
XML Document Object Model (DOM)
PPTX
Jquery fundamentals
PPTX
Xml writers
PPTX
Processing XML and Spreadsheet data in Go
java API for XML DOM
Understanding XML DOM
Simple xml in .net
Part 7
The xml
XMLLec1.pptsfsfsafasfasdfasfdsadfdsfdf dfdsfds
XMLLec1 (1xML lecturefsfsdfsdfdsfdsfsdfsdfdsf
XML stands for EXtensible Markup Language
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Jdom how it works & how it opened the java process
Advanced Web Programming Chapter 12
Xsd restrictions, xsl elements, dhtml
Xml And JSON Java
XML Document Object Model (DOM)
Jquery fundamentals
Xml writers
Processing XML and Spreadsheet data in Go

More from Mohammad Shaker (20)

PDF
12 Rules You Should to Know as a Syrian Graduate
PDF
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
PDF
Interaction Design L06 - Tricks with Psychology
PDF
Short, Matters, Love - Passioneers Event 2015
PDF
Unity L01 - Game Development
PDF
Android L07 - Touch, Screen and Wearables
PDF
Interaction Design L03 - Color
PDF
Interaction Design L05 - Typography
PDF
Interaction Design L04 - Materialise and Coupling
PDF
Android L05 - Storage
PDF
Android L04 - Notifications and Threading
PDF
Android L09 - Windows Phone and iOS
PDF
Interaction Design L01 - Mobile Constraints
PDF
Interaction Design L02 - Pragnanz and Grids
PDF
Android L10 - Stores and Gaming
PDF
Android L06 - Cloud / Parse
PDF
Android L08 - Google Maps and Utilities
PDF
Android L03 - Styles and Themes
PDF
Android L02 - Activities and Adapters
PDF
Android L01 - Warm Up
12 Rules You Should to Know as a Syrian Graduate
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Interaction Design L06 - Tricks with Psychology
Short, Matters, Love - Passioneers Event 2015
Unity L01 - Game Development
Android L07 - Touch, Screen and Wearables
Interaction Design L03 - Color
Interaction Design L05 - Typography
Interaction Design L04 - Materialise and Coupling
Android L05 - Storage
Android L04 - Notifications and Threading
Android L09 - Windows Phone and iOS
Interaction Design L01 - Mobile Constraints
Interaction Design L02 - Pragnanz and Grids
Android L10 - Stores and Gaming
Android L06 - Cloud / Parse
Android L08 - Google Maps and Utilities
Android L03 - Styles and Themes
Android L02 - Activities and Adapters
Android L01 - Warm Up

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
System and Network Administraation Chapter 3
PDF
Designing Intelligence for the Shop Floor.pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
assetexplorer- product-overview - presentation
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
top salesforce developer skills in 2025.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Digital Systems & Binary Numbers (comprehensive )
PPT
Introduction Database Management System for Course Database
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Computer Software and OS of computer science of grade 11.pptx
System and Network Administraation Chapter 3
Designing Intelligence for the Shop Floor.pdf
Transform Your Business with a Software ERP System
assetexplorer- product-overview - presentation
Reimagine Home Health with the Power of Agentic AI​
Navsoft: AI-Powered Business Solutions & Custom Software Development
2025 Textile ERP Trends: SAP, Odoo & Oracle
How to Migrate SBCGlobal Email to Yahoo Easily
Operating system designcfffgfgggggggvggggggggg
Upgrade and Innovation Strategies for SAP ERP Customers
Design an Analysis of Algorithms II-SECS-1021-03
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
top salesforce developer skills in 2025.pdf
CHAPTER 2 - PM Management and IT Context
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Digital Systems & Binary Numbers (comprehensive )
Introduction Database Management System for Course Database

C# Advanced L03-XML+LINQ to XML

  • 1. Mohammad Shaker mohammadshaker.com @ZGTRShaker 2011, 2012, 2013, 2014 C# Advanced L03-XML & LINQ TO XML
  • 2. XML
  • 4. XML •HTML and XHTML? •XML –Extensible Markup Language –A metalanguagethat allows users to define their own customized markup languages, especially in order to display documents on the World Wide Web (WWW). •XSD –XML Schema Definition language •XDR –XML -Data Reduced schemas. •Tags
  • 5. XML <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts>
  • 6. XML <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts>
  • 7. XML <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts> Contacts
  • 8. XML <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts> Contacts
  • 9. XML <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts> Contacts Contact Contact
  • 10. XML <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts> Contacts Mohammad Shaker Hamza Smith
  • 11. XML .NET Classes Class Description XmlNode Represents a single node in a document tree. It is the base of many of the classes shown in this chapter. If this node represents the root of an XML document, you can navigate to any position in the document from it. XmlDocument Extends the XmlNodeclass, but is often the first object you use when using XML. That’s because this class is used to load and save data from disk or elsewhere.
  • 12. XML .NET Classes Class Description XmlElement Represents a single element in the XML document. XmlElementis derived from XmlLinkedNode, which in turn is derived from XmlNode. XmlAttribute Represents a single attribute. Like the XmlDocumentclass, it is derived from the XmlNodeclass. XmlText Represents the text between a starting tag and a closing tag. XmlComment Represents a special kind of node that is not regarded as part of the document other than to provide information to the reader about parts of the document. XmlNodeList Represents a collection of nodes.
  • 13. Creating an XML Node in an XML FileProgrammatically
  • 14. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Create an XML File <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 15. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Create an XML Node users <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 16. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Append the XML Node to the XML File <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 17. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Create an XML Node user <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 18. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Append the node: user to the root node: users <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 19. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Create another XML Node user <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 20. Creating XML Node static void Main(string[] args) { XmlDocumentxmlDoc= new XmlDocument(); XmlNoderootNode= xmlDoc.CreateElement("users"); xmlDoc.AppendChild(rootNode); XmlNodeuserNode= xmlDoc.CreateElement("user"); XmlAttributeattribute = xmlDoc.CreateAttribute("age"); attribute.Value= "42"; userNode.Attributes.Append(attribute); userNode.InnerText= "John Doe"; rootNode.AppendChild(userNode); userNode= xmlDoc.CreateElement("user"); attribute = xmlDoc.CreateAttribute("age"); attribute.Value= "39"; userNode.Attributes.Append(attribute); userNode.InnerText= "Jane Doe"; rootNode.AppendChild(userNode); xmlDoc.Save("test-doc.xml"); } Save the file where you want <users> <user age="42">John Doe</user> <user age="39">Jane Doe</user> </users>
  • 21. Building a Node -A Faster Way? XElementxml=newXElement("contacts", newXElement("contact", newXAttribute("contactId", "2"), newXElement("firstName", "Mohammad"), newXElement("lastName", "Shaker") ), newXElement("contact", newXAttribute("contactId", "3"), newXElement("firstName", "Hamza"), newXElement("lastName", "Smith") ) ); Console.WriteLine(xml);
  • 22. Building a Node -A Faster Way? XElementxml=newXElement("contacts", newXElement("contact", newXAttribute("contactId", "2"), newXElement("firstName", "Mohammad"), newXElement("lastName", "Shaker") ), newXElement("contact", newXAttribute("contactId", "3"), newXElement("firstName", "Hamza"), newXElement("lastName", "Smith") ) ); Console.WriteLine(xml); <contacts> <contactcontactId="2"> <firstName>Mohammad</firstName> <lastName>Shaker</lastName> </contact> <contactcontactId="3"> <firstName>Hamza</firstName> <lastName>Smith</lastName> </contact> </contacts>
  • 28. XML <?xml version="1.0" encoding="utf-8"?> <RoomsCoordProperties> <LocationDimension> 10 </LocationDimension> <Number> 5 </Number> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> <BasicLocationLength> 4 </BasicLocationLength> <Room id="3"> <LocationID> 0 </LocationID> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> </Room> … public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) { XmlDocumentxmlDoc= new XmlDocument(); xmlDoc.Load(XMLFilePath); XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); }
  • 29. XML <?xml version="1.0" encoding="utf-8"?> <RoomsCoordProperties> <LocationDimension> 10 </LocationDimension> <Number> 5 </Number> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> <BasicLocationLength> 4 </BasicLocationLength> <Room id="3"> <LocationID> 0 </LocationID> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> </Room> … public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) { XmlDocumentxmlDoc= new XmlDocument(); xmlDoc.Load(XMLFilePath); XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); }
  • 30. XML <?xml version="1.0" encoding="utf-8"?> <RoomsCoordProperties> <LocationDimension> 10 </LocationDimension> <Number> 5 </Number> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> <BasicLocationLength> 4 </BasicLocationLength> <Room id="3"> <LocationID> 0 </LocationID> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> </Room> … public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) { XmlDocumentxmlDoc= new XmlDocument(); xmlDoc.Load(XMLFilePath); XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); }
  • 31. XML <?xml version="1.0" encoding="utf-8"?> <RoomsCoordProperties> <LocationDimension> 10 </LocationDimension> <Number> 5 </Number> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> <BasicLocationLength> 4 </BasicLocationLength> <Room id="3"> <LocationID> 0 </LocationID> <Width> 12 </Width> <Length> 12 </Length> <Height> 3 </Height> <Opacity> 0.3 </Opacity> </Room> … public static void InitializeRoomFromXMLFile(Room myRoom, introomNumber) { XmlDocumentxmlDoc= new XmlDocument(); xmlDoc.Load(XMLFilePath); XmlNodeListxmlNodeList= xmlDoc.GetElementsByTagName("Room"); myRoom.RoomID= Int32.Parse(xmlNodeList[roomNumber].Attributes[0].FirstChild.Value); myRoom.RoomLocationID= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[0].FirstChild.Value); myRoom.RoomWidth= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[1].FirstChild.Value); myRoom.RoomLength= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[2].FirstChild.Value); myRoom.RoomHeight= Int32.Parse(xmlNodeList[roomNumber].ChildNodes[3].FirstChild.Value); myRoom.RoomOpacity= Double.Parse(xmlNodeList[roomNumber].ChildNodes[4].FirstChild.Value); }
  • 32. LINQ to XMLXML to LINQ
  • 33. LINQ and XML •LINQ to XML •XML to LINQ varquery = from p in people where p.CanCode select new Xelement(“Person”, new Xattribute(“Age”, p.Age), p.Name) varx = new XElement(“People”, from p in people where p.CanCode select new Xelement(“Person”, new Xattribute(“Age”, p.Age), p.Name) )
  • 34. LINQ to XML •Let’s have the following XML file <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 35. LINQ to XML XmlNodesearched=null; XmlDocumentdoc=newXmlDocument(); doc.Load(@"D:Temporarycustomers.xml"); foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) { if(node.Attributes["id"].InnerText=="80") { searched=node; break; } }
  • 36. LINQ to XML XmlNodesearched=null; XmlDocumentdoc=newXmlDocument(); doc.Load(@"D:Temporarycustomers.xml"); foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) { if(node.Attributes["id"].InnerText=="80") { searched=node; break; } } XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Attribute("id") =="80" selectc;
  • 37. LINQ to XML XmlNodesearched=null; XmlDocumentdoc=newXmlDocument(); doc.Load(@"D:Temporarycustomers.xml"); foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) { if(node.Attributes["id"].InnerText=="80") { searched=node; break; } } XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Attribute("id") =="80" selectc; <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 38. LINQ to XML XmlNodesearched=null; XmlDocumentdoc=newXmlDocument(); doc.Load(@"D:Temporarycustomers.xml"); foreach(XmlNodenodeindoc.SelectNodes("/customers/customer")) { if(node.Attributes["id"].InnerText=="80") { searched=node; break; } } XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Attribute("id") =="80" selectc; <customerid="80"> <namevalue="Sample Name 3"/> </customer> <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 39. LINQ to XML XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Element("name").Attribute("value") =="Sample Name" selectc; <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 40. LINQ to XML XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Element("name").Attribute("value") =="Sample Name" selectc; <customerid="84"> <namevalue="Sample Name"/> </customer> <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 41. LINQ to XML XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Attribute("id") =="84" &&(string)c.Element("name").Attribute("value") =="Sample Name" selectc; <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 42. LINQ to XML XElementmain=XElement.Load(@"D:Temporarycustomers.xml"); IEnumerable<XElement>searched= fromcinmain.Elements("customer") where(string)c.Attribute("id") =="84" &&(string)c.Element("name").Attribute("value") =="Sample Name" selectc; <customerid="84"> <namevalue="Sample Name"/> </customer> <customers> <customerid="84"> <namevalue="Sample Name"/> </customer> <customerid="89"> <namevalue="Sample Name 2"/> </customer> <customerid="80"> <namevalue="Sample Name 3"/> </customer> </customers>
  • 43. Performanceof LINQ •LINQ has more control and efficiency in O/R Mapping than NHibernate –LINQ: ExternlMapping or Attribute Mapping –NHibernate: ExternlMapping •Because of mapping, LINQ is lower than database tools such as SqlDataReaderor SqlDataAdapter –In large dataset, their performance are more and more similar
  • 45. XML SerializationNot Always an Easy, Straightforward Task
  • 47. XML SerializationSerialize a class that simply consists of public fields and properties into an XML file
  • 48. XML SerializationUse XML serialization to generate an XML stream that conforms to a specific XML Schema (XSD) document.
  • 50. XML Serialization namespace XMLTest1 { public class Test { public String value1; public String value2; } class Program { static void Main(string[] args) { Test myTest= new Test() { value1 = "Value 1", value2 = "Value 2" }; XmlSerializerx = new XmlSerializer(myTest.GetType()); x.Serialize(Console.Out, myTest); Console.ReadKey(); } } }
  • 51. XML Serialization namespace XMLTest1 { public class Test { public String value1; public String value2; } class Program { static void Main(string[] args) { Test myTest= new Test() { value1 = "Value 1", value2 = "Value 2" }; XmlSerializerx = new XmlSerializer(myTest.GetType()); x.Serialize(Console.Out, myTest); Console.ReadKey(); } } } <?xml version="1.0" encoding="ibm850"?> <Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <value1>Value 1</value1> <value2>Value 2</value2> </Test> That’s Cool!
  • 53. XML DeSerialization namespace XMLTest1 { public class Test { public String value1; public String value2; } class Program { static void Main(string[] args) { String xData= "<?xml version="1.0" encoding="ibm850"?><Test xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><value1>Value 1</value1><value2>Value 2</value2></Test>"; XmlSerializerx = new XmlSerializer(typeof(Test)); Test myTest= (Test)x.Deserialize(new StringReader(xData)); Console.WriteLine("V1: " + myTest.value1); Console.WriteLine("V2: " + myTest.value2); Console.ReadKey(); } } }
  • 54. XML DeSerialization namespace XMLTest1 { public class Test { public String value1; public String value2; } class Program { static void Main(string[] args) { String xData= "<?xml version="1.0" encoding="ibm850"?><Test xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><value1>Value 1</value1><value2>Value 2</value2></Test>"; XmlSerializerx = new XmlSerializer(typeof(Test)); Test myTest= (Test)x.Deserialize(new StringReader(xData)); Console.WriteLine("V1: " + myTest.value1); Console.WriteLine("V2: " + myTest.value2); Console.ReadKey(); } } }
  • 55. XML Serialization and Attributes
  • 56. XML Serialization and Attributes [XmlRoot("XTest")] public class Test { [XmlElement(ElementName="V1")] public String value1; [XmlElement(ElementName="V2")] public String value2; [XmlArray("OtherValues")] [XmlArrayItem("OValue")] public List others = new List(); }
  • 57. XML Serialization and Attributes [XmlRoot("XTest")] public class Test { [XmlElement(ElementName="V1")] public String value1; [XmlElement(ElementName="V2")] public String value2; [XmlArray("OtherValues")] [XmlArrayItem("OValue")] public List others = new List(); } <?xml version="1.0" encoding="ibm850"?> <XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <V1>A1</V1> <V2>B1</V2> <OtherValues> <OValue>Test</OValue> </OtherValues> </XTest>
  • 58. XML Serialization and Attributes [XmlRoot("XTest")] public class Test { [XmlElement(ElementName="V1")] public String value1; [XmlElement(ElementName="V2")] public String value2; [XmlArray("OtherValues")] [XmlArrayItem("OValue")] public List others = new List(); } <?xml version="1.0" encoding="ibm850"?> <XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <V1>A1</V1> <V2>B1</V2> <OtherValues> <OValue>Test</OValue> </OtherValues> </XTest>
  • 59. XML Serialization and Attributes [XmlRoot("XTest")] public class Test { [XmlElement(ElementName="V1")] public String value1; [XmlElement(ElementName="V2")] public String value2; [XmlArray("OtherValues")] [XmlArrayItem("OValue")] public List others = new List(); } <?xml version="1.0" encoding="ibm850"?> <XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <V1>A1</V1> <V2>B1</V2> <OtherValues> <OValue>Test</OValue> </OtherValues> </XTest>
  • 60. XML Serialization and Attributes [XmlRoot("XTest")] public class Test { [XmlElement(ElementName="V1")] public String value1; [XmlElement(ElementName="V2")] public String value2; [XmlArray("OtherValues")] [XmlArrayItem("OValue")] public List others = new List(); } <?xml version="1.0" encoding="ibm850"?> <XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <V1>A1</V1> <V2>B1</V2> <OtherValues> <OValue>Test</OValue> </OtherValues> </XTest>
  • 61. XML Serialization and Attributes [XmlRoot("XTest")] public class Test { [XmlElement(ElementName="V1")] public String value1; [XmlElement(ElementName="V2")] public String value2; [XmlArray("OtherValues")] [XmlArrayItem("OValue")] public List others = new List(); } <?xml version="1.0" encoding="ibm850"?> <XTestxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <V1>A1</V1> <V2>B1</V2> <OtherValues> <OValue>Test</OValue> </OtherValues> </XTest>
  • 63. XML DocumentationC# provides a mechanism for developers to document their code using XML. In source code files, lines that begin with ///and that precede a user-defined type such as a class, delegate, or interface; a member such as a field, event, property, or method; or a namespace declaration can be processed as comments and placed in a file.
  • 64. XML Documentation /// <summary> /// Class level summary documentation goes here.</summary> /// <remarks> /// Longer comments can be associated with a type or member /// through the remarks tag</remarks> public class SomeClass { /// <summary> /// Store for the name property</summary> private string myName= null; /// <summary> /// The class constructor. </summary> public SomeClass() { // TODO: Add Constructor Logic here } /// <summary> /// Name property </summary> /// <value> /// A value tag is used to describe the property value</value> public string Name { get { return myName; } } /// <summary> /// Description for SomeMethod.</summary> /// <paramname="s"> Parameter description for s goes here</param> /// <seealsocref="String"> /// You can use the crefattribute on any tag to reference a type or member /// and the compiler will check that the reference exists. </seealso> public void SomeMethod(string s) { }
  • 65. XML Documentation /// <summary> /// Class level summary documentation goes here.</summary> /// <remarks> /// Longer comments can be associated with a type or member /// through the remarks tag</remarks> public class SomeClass { /// <summary> /// Store for the name property</summary> private string myName= null; /// <summary> /// The class constructor. </summary> public SomeClass() { // TODO: Add Constructor Logic here } /// <summary> /// Name property </summary> /// <value> /// A value tag is used to describe the property value</value> public string Name { get { return myName; } } /// <summary> /// Description for SomeMethod.</summary> /// <paramname="s"> Parameter description for s goes here</param> /// <seealsocref="String"> /// You can use the crefattribute on any tag to reference a type or member /// and the compiler will check that the reference exists. </seealso> public void SomeMethod(string s) { }
  • 66. XML Documentation /// <summary> /// Class level summary documentation goes here.</summary> /// <remarks> /// Longer comments can be associated with a type or member /// through the remarks tag</remarks> public class SomeClass { /// <summary> /// Store for the name property</summary> private string myName= null; /// <summary> /// The class constructor. </summary> public SomeClass() { // TODO: Add Constructor Logic here } /// <summary> /// Name property </summary> /// <value> /// A value tag is used to describe the property value</value> public string Name { get { return myName; } } /// <summary> /// Description for SomeMethod.</summary> /// <paramname="s"> Parameter description for s goes here</param> /// <seealsocref="String"> /// You can use the crefattribute on any tag to reference a type or member /// and the compiler will check that the reference exists. </seealso> public void SomeMethod(string s) { } <?xml version="1.0"?> <doc> <assembly> <name>xmlsample</name> </assembly> <members> <member name="T:SomeClass"> <summary> Class level summary documentation goes here. </summary> <remarks> Longer comments can be associated with a type or member through the remarks tag </remarks> </member> <member name="F:SomeClass.myName"> <summary> Store for the name property </summary> </member> <member name="M:SomeClass.#ctor"> <summary>The class constructor.</summary> </member> <member name="M:SomeClass.SomeMethod(System.String)"> <summary>Description for SomeMethod.</summary> <paramname="s"> Parameter description for s goes here</param> <seealsocref="T:System.String"> You can use the crefattribute on any tag to reference a type or member and the compiler will check that the reference exists. </seealso> </member> …. </doc>
  • 67. XML Documentation /// <summary> /// Class level summary documentation goes here.</summary> /// <remarks> /// Longer comments can be associated with a type or member /// through the remarks tag</remarks> public class SomeClass { /// <summary> /// Store for the name property</summary> private string myName= null; /// <summary> /// The class constructor. </summary> public SomeClass() { // TODO: Add Constructor Logic here } /// <summary> /// Name property </summary> /// <value> /// A value tag is used to describe the property value</value> public string Name { get { return myName; } } /// <summary> /// Description for SomeMethod.</summary> /// <paramname="s"> Parameter description for s goes here</param> /// <seealsocref="String"> /// You can use the crefattribute on any tag to reference a type or member /// and the compiler will check that the reference exists. </seealso> public void SomeMethod(string s) { } <?xml version="1.0"?> <doc> <assembly> <name>xmlsample</name> </assembly> <members> <member name="T:SomeClass"> <summary> Class level summary documentation goes here. </summary> <remarks> Longer comments can be associated with a type or member through the remarks tag </remarks> </member> <member name="F:SomeClass.myName"> <summary> Store for the name property </summary> </member> <member name="M:SomeClass.#ctor"> <summary>The class constructor.</summary> </member> <member name="M:SomeClass.SomeMethod(System.String)"> <summary>Description for SomeMethod.</summary> <paramname="s"> Parameter description for s goes here</param> <seealsocref="T:System.String"> You can use the crefattribute on any tag to reference a type or member and the compiler will check that the reference exists. </seealso> </member> …. </doc>
  • 68. XML Documentation •To build the XML Documentation sample –To generate the sample XML documentation, type the following at the command prompt: •cscXMLsample.cs/doc:XMLsample.xml –To see the generated XML, issue the following command: •type XMLsample.xml