Serializing .NET Objects to XML: An Example in C#
290 likes | 419 Views
This guide demonstrates how to serialize .NET objects to XML using the System.Xml.Serialization namespace. We'll create a simple class, `Node`, containing stock and option prices, and serialize it to an XML file named "Node.xml". We'll also explore an example of a web service that returns a `Node` object. This process showcases how to define XML elements with attributes and deserialize XML into .NET objects. Suitable for developers looking to integrate XML processing in their applications.
Serializing .NET Objects to XML: An Example in C#
E N D
Presentation Transcript
From Objects to XML using System; using System.Xml.Serialization; using System.IO; namespace XmlTest { public class Node { private double stockPrice; private double optionPrice; public double StockPrice { get { return stockPrice; } set { stockPrice = value; } }
public double OptionPrice { get { return optionPrice; } set { optionPrice = value; } } } public class XmlMain { static void Main(string[] args) { Node n = new Node(); n.StockPrice = 100.0; n.OptionPrice = 3.00;
XmlSerializer xs = new XmlSerializer(typeof(Node)); Stream s = File.OpenWrite("Node.xml"); xs.Serialize(s,n); s.Close(); } } }
Node.xml <?xml version="1.0"?> <Node xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <StockPrice>100</StockPrice> <OptionPrice>3</OptionPrice> </Node>
Controlling Serialization using System; using System.Xml.Serialization; using System.IO; namespace XmlTest { [XmlRoot("TreeNode")] public class Node { private double stockPrice; private double optionPrice;
[XmlElement("sp")] public double StockPrice { get { return stockPrice; } set { stockPrice = value; } } [XmlElement("op")] public double OptionPrice { get { return optionPrice; } set { optionPrice = value; } } }
public class XmlMain { static void Main(string[] args) { Node n = new Node(); n.StockPrice = 100.0; n.OptionPrice = 3.00; XmlSerializer xs = new XmlSerializer(typeof(Node)); Stream s = File.OpenWrite("Node.xml"); xs.Serialize(s,n); s.Close(); } } }
Node.xml <?xml version="1.0"?> <TreeNode xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <sp>100</sp> <op>3</op> </TreeNode>e>3</OptionPrice> </Node>
XMLSerializer in Web Services // NodeService.cs using System; using System.Web.Services; namespace XMLWebService { public class NodeService : System.Web.Services.WebService { [WebMethod] public Node getNode() { return new Node(100.0,3.0); } }
public class Node { private double stockPrice; private double optionPrice; public double StockPrice { get { return stockPrice; } set { stockPrice = value; } } public double OptionPrice { get { return optionPrice; } set { optionPrice = value; } } public Node(double sp, double op) { StockPrice = sp; OptionPrice = op; }
// required for web service public Node() { StockPrice = 0.0; OptionPrice = 0.0; } } public class XmlMain { public static void Main(string[] args) { NodeService ns = new NodeService(); Node n = ns.getNode(); Console.WriteLine(n.OptionPrice); } } }
ACoolNodeService.asmx <%@ WebService Language="C#“ Class="XMLWebService.NodeService" %> • Place in a directory above bin • In the bin directory place the compiled .dll file NodeService.dll • Run IIS and choose default web site • Action/New/Virtual Directory and set an alias to the directory containing the .asmx file (above bin)
Response in a browser <?xml version="1.0" encoding="utf-8"?> <Node xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/"> <StockPrice>100</StockPrice> <OptionPrice>3</OptionPrice> </Node>
Client Side • Get the wsdl with a browser • Run wsdl.exe • Compile output of wsdl to a .dll • Compile client and reference the .dll • Run the client
using System; public class ClientMain { public static void Main() { NodeService ns = new NodeService(); Node n = ns.getNode(); Console.WriteLine(n.OptionPrice + " " + n.StockPrice); } } ..\46-690\examples\XMLSerialization\webservices\client>ClientMain 3 100
Basic XML Processing // XmlTextReader Demo using System.Xml; using System.IO; using System; class XmlDemo { static void Main() { String xml = "<student><score>100</score></student>"; XmlTextReader xmlTextReader = new XmlTextReader( new StringReader(xml));
// build an empty DOM tree XmlDocument doc = new XmlDocument(); // load the tree from a string doc.Load(xmlTextReader); // get the root of the xml XmlElement root = doc.DocumentElement; // write its value Console.WriteLine(root.Name); // point at the child element XmlElement score = (XmlElement)root.FirstChild;
// write the element name Console.WriteLine(score.Name); // point to its child XmlText value = (XmlText) score.FirstChild; // look at the contents of the text node Console.WriteLine(value.Value); } } XmlDemo.exe student score 100
Reading a file FixedFloatSwap.xml <?xml version="1.0" encoding="UTF-8"?> <FixedFloatSwap> <Bank>Bank of London</Bank> <Notional currency = "pounds">100</Notional> <Fixed_Rate>5</Fixed_Rate> <NumYears>3</NumYears> <NumPayments>6</NumPayments> </FixedFloatSwap>
// Reading any XML file using System.Xml; using System.IO; using System; class XmlDemo { static void Main() { XmlTextReader reader = new XmlTextReader("FixedFloatSwap.xml");
while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: Console.WriteLine("XmlDeclaration"); break; case XmlNodeType.ProcessingInstruction: Console.WriteLine("ProcessingInstruction"); break; case XmlNodeType.DocumentType: Console.WriteLine("DocumentType"); break; case XmlNodeType.Comment: Console.WriteLine("Comment"); break;
case XmlNodeType.Element: Console.WriteLine("Element"); if (reader.HasAttributes) Console.WriteLine("Attributes found"); break; case XmlNodeType.Text: Console.WriteLine("Text"); break; case XmlNodeType.Whitespace: Console.WriteLine("Whitespace"); break; } } } }
D:\McCarthy\www\46-690\examples\XmlProcessing>XmlURLDemo XmlDeclaration Whitespace Element Whitespace Element Text Whitespace Element Attributes found Text Whitespace Element Text Whitespace Element Text Whitespace Element Text Whitespace
Reading from the net • Suppose the FixedFloatSwap.xml is found At http://localhost/FpML/FixedFloatSwap.xml • To do that, simply place the FixedFloatSwap.xml file in a directory and create a virtual directory in IIS. This directory would have the alias FpML.
// Reading any XML file from a URL using System.Xml; using System.IO; using System; class XmlDemo { static void Main() { XmlTextReader reader = new XmlTextReader("http://localhost/FpML/FixedFloatSwap.xml"); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: Console.WriteLine("XmlDeclaration"); break;
case XmlNodeType.ProcessingInstruction: Console.WriteLine("ProcessingInstruction"); break; case XmlNodeType.DocumentType: Console.WriteLine("DocumentType"); break; case XmlNodeType.Comment: Console.WriteLine("Comment"); break; case XmlNodeType.Element: Console.WriteLine("Element"); if (reader.HasAttributes) Console.WriteLine("Attributes found"); break;
case XmlNodeType.Text: Console.WriteLine("Text"); break; case XmlNodeType.Whitespace: Console.WriteLine("Whitespace"); break; } } } }
D:\McCarthy\www\46-690\examples\XmlProcessing>XmlURLDemo XmlDeclaration Whitespace Element Whitespace Element Text Whitespace Element Attributes found Text Whitespace Element Text Whitespace Element Text Whitespace Element Text Whitespace