c# advanced l03-xml+linq to xml

68
Mohammad Shaker mohammadshaker.com @ZGTRShaker 2011, 2012, 2013, 2014 C# Advanced L03-XML & LINQ TO XML

Upload: mohammad-shaker

Post on 13-Jan-2015

237 views

Category:

Software


5 download

DESCRIPTION

C# Advanced L03-XML+LINQ to XML

TRANSCRIPT

Page 1: C# Advanced L03-XML+LINQ to XML

Mohammad Shaker

mohammadshaker.com

@ZGTRShaker

2011, 2012, 2013, 2014

C# AdvancedL03-XML & LINQ TO XML

Page 2: C# Advanced L03-XML+LINQ to XML

XML

Page 3: C# Advanced L03-XML+LINQ to XML

XML – The Definition

Page 4: C# Advanced L03-XML+LINQ to XML

XML

• HTML and XHTML?

• XML– Extensible Markup Language

– A metalanguage that 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

Page 5: C# Advanced L03-XML+LINQ to XML

XML

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Page 6: C# Advanced L03-XML+LINQ to XML

XML

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Page 7: C# Advanced L03-XML+LINQ to XML

XML

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Contacts

Page 8: C# Advanced L03-XML+LINQ to XML

XML

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Contacts

Page 9: C# Advanced L03-XML+LINQ to XML

XML

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Contacts

Contact Contact

Page 10: C# Advanced L03-XML+LINQ to XML

XML

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Contacts

MohammadShaker

HamzaSmith

Page 11: C# Advanced L03-XML+LINQ to XML

XML .NET Classes

Class Description

XmlNodeRepresents a single node in a document tree. It is the base of many of theclasses shown in this chapter. If this node represents the root of an XMLdocument, you can navigate to any position in the document from it.

XmlDocumentExtends the XmlNode class, but is often the first object you use when usingXML. That’s because this class is used to load and save data from disk orelsewhere.

Page 12: C# Advanced L03-XML+LINQ to XML

XML .NET Classes

Class Description

XmlElementRepresents a single element in the XML document. XmlElement is derivedfrom XmlLinkedNode, which in turn is derived from XmlNode.

XmlAttributeRepresents a single attribute. Like the XmlDocument class, it is derived fromthe XmlNode class.

XmlText Represents the text between a starting tag and a closing tag.

XmlCommentRepresents a special kind of node that is not regarded as part of the documentother than to provide information to the reader about parts of the document.

XmlNodeList Represents a collection of nodes.

Page 13: C# Advanced L03-XML+LINQ to XML

Creating an XML Node in an XML FileProgrammatically

Page 14: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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>

Page 15: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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 Nodeusers

<users><user age="42">John Doe</user><user age="39">Jane Doe</user>

</users>

Page 16: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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>

Page 17: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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 Nodeuser

<users><user age="42">John Doe</user><user age="39">Jane Doe</user>

</users>

Page 18: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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>

Page 19: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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>

Page 20: C# Advanced L03-XML+LINQ to XML

Creating XML Nodestatic void Main(string[] args){

XmlDocument xmlDoc = new XmlDocument();XmlNode rootNode = xmlDoc.CreateElement("users");xmlDoc.AppendChild(rootNode);

XmlNode userNode = xmlDoc.CreateElement("user");XmlAttribute attribute = 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>

Page 21: C# Advanced L03-XML+LINQ to XML

Building a Node - A Faster Way?

XElement xml = new XElement("contacts",new XElement("contact",

new XAttribute("contactId", "2"),new XElement("firstName", "Mohammad"),new XElement("lastName", "Shaker")

),new XElement("contact",

new XAttribute("contactId", "3"),new XElement("firstName", "Hamza"),new XElement("lastName", "Smith")

));

Console.WriteLine(xml);

Page 22: C# Advanced L03-XML+LINQ to XML

Building a Node - A Faster Way?

XElement xml = new XElement("contacts",new XElement("contact",

new XAttribute("contactId", "2"),new XElement("firstName", "Mohammad"),new XElement("lastName", "Shaker")

),new XElement("contact",

new XAttribute("contactId", "3"),new XElement("firstName", "Hamza"),new XElement("lastName", "Smith")

));

Console.WriteLine(xml);

<contacts><contact contactId="2">

<firstName>Mohammad</firstName><lastName>Shaker</lastName>

</contact><contact contactId="3">

<firstName>Hamza</firstName><lastName>Smith</lastName>

</contact></contacts>

Page 23: C# Advanced L03-XML+LINQ to XML

Searching an XML

Page 24: C# Advanced L03-XML+LINQ to XML

XML

• Selecting Nodes

Page 25: C# Advanced L03-XML+LINQ to XML

XML

• Selecting Nodes

Page 26: C# Advanced L03-XML+LINQ to XML

XML

• Selecting Nodes

Page 27: C# Advanced L03-XML+LINQ to XML

Getting XML Node Values

Page 28: C# Advanced L03-XML+LINQ to XML

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, int roomNumber){

XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(XMLFilePath);

XmlNodeList xmlNodeList = 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);

}

Page 29: C# Advanced L03-XML+LINQ to XML

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, int roomNumber){

XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(XMLFilePath);

XmlNodeList xmlNodeList = 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);

}

Page 30: C# Advanced L03-XML+LINQ to XML

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, int roomNumber){

XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(XMLFilePath);

XmlNodeList xmlNodeList = 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);

}

Page 31: C# Advanced L03-XML+LINQ to XML

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, int roomNumber){

XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load(XMLFilePath);

XmlNodeList xmlNodeList = 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);

}

Page 32: C# Advanced L03-XML+LINQ to XML

LINQ to XMLXML to LINQ

Page 33: C# Advanced L03-XML+LINQ to XML

LINQ and XML

• LINQ to XML

• XML to LINQ

var query = from p in peoplewhere p.CanCodeselect new Xelement(“Person”, new Xattribute(“Age”, p.Age), p.Name)

var x = new XElement(“People”, from p in peoplewhere p.CanCodeselect new Xelement(“Person”, new Xattribute(“Age”, p.Age), p.Name)

)

Page 34: C# Advanced L03-XML+LINQ to XML

LINQ to XML

• Let’s have the following XML file

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 35: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XmlNode searched = null;XmlDocument doc = new XmlDocument();doc.Load(@"D:\Temporary\customers.xml");

foreach (XmlNode node in doc.SelectNodes("/customers/customer")){

if (node.Attributes["id"].InnerText == "80"){

searched = node;break;

}}

Page 36: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XmlNode searched = null;XmlDocument doc = new XmlDocument();doc.Load(@"D:\Temporary\customers.xml");

foreach (XmlNode node in doc.SelectNodes("/customers/customer")){

if (node.Attributes["id"].InnerText == "80"){

searched = node;break;

}}

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Attribute("id") == "80"select c;

Page 37: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XmlNode searched = null;XmlDocument doc = new XmlDocument();doc.Load(@"D:\Temporary\customers.xml");

foreach (XmlNode node in doc.SelectNodes("/customers/customer")){

if (node.Attributes["id"].InnerText == "80"){

searched = node;break;

}}

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Attribute("id") == "80"select c;

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 38: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XmlNode searched = null;XmlDocument doc = new XmlDocument();doc.Load(@"D:\Temporary\customers.xml");

foreach (XmlNode node in doc.SelectNodes("/customers/customer")){

if (node.Attributes["id"].InnerText == "80"){

searched = node;break;

}}

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Attribute("id") == "80"select c; <customer id="80">

<name value="Sample Name 3" /></customer>

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 39: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Element("name").Attribute("value") == "Sample Name"select c;

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 40: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Element("name").Attribute("value") == "Sample Name"select c;

<customer id="84"><name value="Sample Name" />

</customer>

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 41: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Attribute("id") == "84"&& (string)c.Element("name").Attribute("value") == "Sample Name"select c;

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 42: C# Advanced L03-XML+LINQ to XML

LINQ to XML

XElement main = XElement.Load(@"D:\Temporary\customers.xml");

IEnumerable<XElement> searched =from c in main.Elements("customer")where (string)c.Attribute("id") == "84"&& (string)c.Element("name").Attribute("value") == "Sample Name"select c;

<customer id="84"><name value="Sample Name" />

</customer>

<customers><customer id="84"><name value="Sample Name" />

</customer>

<customer id="89"><name value="Sample Name 2" />

</customer>

<customer id="80"><name value="Sample Name 3" />

</customer></customers>

Page 43: C# Advanced L03-XML+LINQ to XML

Performance of LINQ

• LINQ has more control and efficiency in O/R Mapping than NHibernate

– LINQ: Externl Mapping or Attribute Mapping

– NHibernate: Externl Mapping

• Because of mapping, LINQ is lower than database tools such as SqlDataReaderor SqlDataAdapter

– In large dataset, their performance are more and more similar

Page 44: C# Advanced L03-XML+LINQ to XML

XML Serialization

Page 45: C# Advanced L03-XML+LINQ to XML

XML SerializationNot Always an Easy, Straightforward Task

Page 46: C# Advanced L03-XML+LINQ to XML

XML SerializationWhy to?

Page 47: C# Advanced L03-XML+LINQ to XML

XML SerializationSerialize a class that simply consists of public fields and properties into an XML file

Page 48: C# Advanced L03-XML+LINQ to XML

XML SerializationUse XML serialization to generate an XML stream that conforms

to a specific XML Schema (XSD) document.

Page 49: C# Advanced L03-XML+LINQ to XML

Test CaseSerializing a Class

Page 50: C# Advanced L03-XML+LINQ to XML

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" };XmlSerializer x = new XmlSerializer(myTest.GetType());x.Serialize(Console.Out, myTest);Console.ReadKey();

}}

}

Page 51: C# Advanced L03-XML+LINQ to XML

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" };XmlSerializer x = 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!

Page 52: C# Advanced L03-XML+LINQ to XML

Test CaseDeSerializing a Class

Page 53: C# Advanced L03-XML+LINQ to XML

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>";

XmlSerializer x = new XmlSerializer(typeof(Test));Test myTest = (Test)x.Deserialize(new StringReader(xData));Console.WriteLine("V1: " + myTest.value1);Console.WriteLine("V2: " + myTest.value2);Console.ReadKey();

}}

}

Page 54: C# Advanced L03-XML+LINQ to XML

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>";

XmlSerializer x = new XmlSerializer(typeof(Test));Test myTest = (Test)x.Deserialize(new StringReader(xData));Console.WriteLine("V1: " + myTest.value1);Console.WriteLine("V2: " + myTest.value2);Console.ReadKey();

}}

}

Page 55: C# Advanced L03-XML+LINQ to XML

XML Serialization and Attributes

Page 56: C# Advanced L03-XML+LINQ to XML

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();

}

Page 57: C# Advanced L03-XML+LINQ to XML

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"?><XTest xmlns: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>

Page 58: C# Advanced L03-XML+LINQ to XML

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"?><XTest xmlns: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>

Page 59: C# Advanced L03-XML+LINQ to XML

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"?><XTest xmlns: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>

Page 60: C# Advanced L03-XML+LINQ to XML

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"?><XTest xmlns: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>

Page 61: C# Advanced L03-XML+LINQ to XML

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"?><XTest xmlns: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>

Page 62: C# Advanced L03-XML+LINQ to XML

XML Documentation

Page 63: C# Advanced L03-XML+LINQ to XML

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.

Page 64: C# Advanced L03-XML+LINQ to XML

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>/// <param name="s"> Parameter description for s goes here</param>/// <seealso cref="String">/// You can use the cref attribute on any tag to reference a type or member /// and the compiler will check that the reference exists. </seealso>public void SomeMethod(string s) { }

Page 65: C# Advanced L03-XML+LINQ to XML

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>/// <param name="s"> Parameter description for s goes here</param>/// <seealso cref="String">/// You can use the cref attribute on any tag to reference a type or member /// and the compiler will check that the reference exists. </seealso>public void SomeMethod(string s) { }

Page 66: C# Advanced L03-XML+LINQ to XML

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>/// <param name="s"> Parameter description for s goes here</param>/// <seealso cref="String">/// You can use the cref attribute 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><param name="s"> Parameter description for s goes here</param><seealso cref="T:System.String">You can use the cref attribute on any tag to reference a type

or member and the compiler will check that the reference exists.

</seealso></member>

….</doc>

Page 67: C# Advanced L03-XML+LINQ to XML

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>/// <param name="s"> Parameter description for s goes here</param>/// <seealso cref="String">/// You can use the cref attribute 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><param name="s"> Parameter description for s goes here</param><seealso cref="T:System.String">You can use the cref attribute on any tag to reference a type

or member and the compiler will check that the reference exists.

</seealso></member>

….</doc>

Page 68: C# Advanced L03-XML+LINQ to XML

XML Documentation

• To build the XML Documentation sample

– To generate the sample XML documentation, type the following at the command prompt:

• csc XMLsample.cs /doc:XMLsample.xml

– To see the generated XML, issue the following command:

• type XMLsample.xml