c# advanced l03-xml+linq to xml

Post on 13-Jan-2015

237 Views

Category:

Software

5 Downloads

Preview:

Click to see full reader

DESCRIPTION

C# Advanced L03-XML+LINQ to XML

TRANSCRIPT

Mohammad Shaker

mohammadshaker.com

@ZGTRShaker

2011, 2012, 2013, 2014

C# AdvancedL03-XML & LINQ TO XML

XML

XML – The Definition

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

XML

<contacts><contact contactId="2">

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

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

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

</contact></contacts>

XML

<contacts><contact contactId="2">

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

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

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

</contact></contacts>

XML

<contacts><contact contactId="2">

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

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

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

</contact></contacts>

Contacts

XML

<contacts><contact contactId="2">

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

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

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

</contact></contacts>

Contacts

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

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

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.

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.

Creating an XML Node in an XML FileProgrammatically

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>

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>

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>

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>

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>

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>

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>

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

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>

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

}

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

}

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

}

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

}

LINQ to XMLXML to LINQ

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)

)

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>

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;

}}

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;

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>

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>

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>

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>

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>

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>

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

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

Test CaseDeSerializing a 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>";

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

}}

}

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

}}

}

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

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>

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>

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>

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>

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>/// <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 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 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>

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>

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

top related