how do I serialize a xml node in c# - c#

I have a xml node.
<Region Region_Sequence="1" Region_Name="Vadodra" Region_Code="VAD"/>
how can I serialize this xmlnode to my region class
using c# and asp.net

You can do the following:
using System.Xml.Linq;
namespace XMLParser
{
class ParseXML
{
public void ParseXML(string strXML)
{
XDocument xdoc = XDocument.Load(strXML);
var region= from regions in xdoc.Element("Region");
Region objRegion=new Region();
Region.Region_Name=region.Element("Region_Name").Value.ToString();
}
}
}

Something like this:
string xml = "<Region Region_Sequence=\"1\" Region_Name=\"Vadodra\" Region_Code=\"VAD\"/>"
var serializer = new XmlSerializer(typeof(Region));
Region result;
using (TextReader reader = new StringReader(xml))
{
result = (Region)serializer.Deserialize(reader);
}

Related

How to do my XML Document to looks like the example in C# .NET 2.0?

How to make my XML Document to looks like the following:
<?xml version="1.0" encoding="utf-8" ?>
<Diff>
<Delete file="file0.ext"/>
<Create file="file1.ext"/>
<Create dir="dir1"/>
<Create dir="dir1\dir2"/>
<Create file="dir1\dir2\file2.ext"/>
</Diff>
If i start from this :
static class DirectoryComparer
{
public static XmlDocument Compare(string oldPath, string newPath)
{
XmlDocument xml = new XmlDocument();
// TODO: Needs to fill "xml" here
return xml;
}
}
The XmlDocument instance has a CreateElement method that allows you to create elements for your XmlDocument instance. The newly created Element (that is an XmlNode) can then be added to the Document Object Model by calling AppendChild. The Element has a SetAttribute methode to add attributes to the element.
Combining all that an implementation to get exactly your example XML might loo like this:
static class DirectoryComparer
{
public static XmlDocument Compare(string oldPath, string newPath)
{
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateXmlDeclaration("1.0", "utf-8", null));
XmlElement diff = xml.CreateElement("Diff");
xml.AppendChild(diff);
diff.AppendChild(DeleteFile(xml,"file0.ext"));
diff.AppendChild(CreateFile(xml,"file1.ext"));
diff.AppendChild(CreateDir(xml,"dir1"));
diff.AppendChild(CreateDir(xml,#"dir1\dir2"));
diff.AppendChild(CreateFile(xml,#"dir1\dir2\file2.ext"));
return xml;
}
private static XmlElement DeleteFile(XmlDocument xml, string file)
{
XmlElement delete = xml.CreateElement("Delete");
delete.SetAttribute("file", file);
return delete;
}
private static XmlElement CreateFile(XmlDocument xml, string file)
{
return CreateFileOrDir(xml, "file", file);
}
private static XmlElement CreateDir(XmlDocument xml, string dir)
{
return CreateFileOrDir(xml, "dir", dir);
}
private static XmlElement CreateFileOrDir(XmlDocument xml, string attribute,string value)
{
XmlElement create = xml.CreateElement("Create");
create.SetAttribute(attribute, value);
return create;
}
}
And when run from LinqPad the output looks like this:
Using Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication40
{
class Program
{
const string FILENAME = #"c:\temp\test.csv";
static void Main(string[] args)
{
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Diff></Diff>";
XDocument doc = XDocument.Parse(ident);
XElement root = doc.Root;
root.Add(new object[] {
new XElement("Delete", new XAttribute("file", "file0.ext")),
new XElement("Create", new XAttribute("file", "file1.ext")),
new XElement("Create", new XAttribute("dir", "dir1")),
new XElement("Create", new XAttribute("dir", "dir2")),
new XElement("Create", new XAttribute("file", #"dir1\dir2\file2.ext"))
});
doc.Save(FILENAME);
}
}
}

C# - parse xml nodes

I am loading my data from XML using C# this way:
XmlDocument xmlDoc = new XmlDocument();
TextAsset xmlFile = Resources.Load("levels/" + levelID) as TextAsset;
xmlDoc.LoadXml(xmlFile.text);
XmlNodeList levelsList = xmlDoc.GetElementsByTagName("level");
foreach (XmlNode levelInfo in levelsList)
{
XmlNodeList childNodes = levelInfo.ChildNodes;
foreach (XmlNode value in childNodes)
{
switch (value.Name)
{
case "info":
//levelWidth = getInt(value, 0);
//levelHeight = getInt(value, 1);
break;
}
}
}
And heres XML I am loading:
<?xml version="1.0" encoding="utf-8" ?>
<level>
<info w="1000" h="500"/>
</level>
It works just fine, I am now trying to find best way to load child nodes, inside my level node with multiple points nodes inside
<?xml version="1.0" encoding="utf-8" ?>
<level>
<info w="1000" h="500"/>
<ground>
<point val1="val1" val2="val2"/>
</ground>
</level>
I will be grateful for some guidance how to move in the right direction, thank you.
Using XML Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
"<level>" +
"<info w=\"1000\" h=\"500\"/>" +
"</level>";
XDocument doc = XDocument.Parse(xml);
XElement level = (XElement)doc.FirstNode;
level.Add("ground", new object[] {
new XElement("point", new XAttribute[] {
new XAttribute("val1", "val1"),
new XAttribute("val2", "val2")
})
});
}
}
}
​
If you need read all points, you can use
var nodeList = Xmldocument.SelectNodes("level/info/ground/point");
SelectNodes return a list of nodes.
I would go for a slidely different way and use a data object. Then you don't have to analyse xml, you just code your data class:
[Serializable()]
public class CLevel
{
public string Info { get; set; }
}
[Serializable()]
public class CDatafile
{
public List<CLevel> LevelList { get; set; }
public CDatafile()
{
LevelList = new List<CLevel>();
}
}
public class DataManager
{
private string FileName = "Data.xml";
public CDatafile Datafile { get; set; }
public DataManager()
{
Datafile = new CDatafile();
}
// Load file
public void LoadFile()
{
if (System.IO.File.Exists(FileName))
{
System.IO.StreamReader srReader = System.IO.File.OpenText(FileName);
Type tType = Datafile.GetType();
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
object oData = xsSerializer.Deserialize(srReader);
Datafile = (CDatafile)oData;
srReader.Close();
}
}
// Save file
public void SaveFile()
{
System.IO.StreamWriter swWriter = System.IO.File.CreateText(FileName);
Type tType = Datafile.GetType();
if (tType.IsSerializable)
{
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
xsSerializer.Serialize(swWriter, Datafile);
swWriter.Close();
}
}
Then you can use it to create, save and load the file like this:
DataManager dataMng = new DataManager();
// Create some data
CLevel level = new CLevel();
level.Info = "Testlevel";
dataMng.Datafile.LevelList.Add(level);
// Save to file
dataMng.SaveFile();
// Load from file
dataMng.LoadFile();
So you can do everything in code checked by the compiler. Makes life a lot easier, or what do you think?

Xml Serialization without XML Declaration [duplicate]

How do I serialize an XML-serializable object to an XML fragment (no XML declaration nor namespace references in the root element)?
Here is a hack-ish way to do it without having to load the entire output string into an XmlDocument:
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public class Example
{
public String Name { get; set; }
static void Main()
{
Example example = new Example { Name = "Foo" };
XmlSerializer serializer = new XmlSerializer(typeof(Example));
XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
emptyNamespace.Add(String.Empty, String.Empty);
StringBuilder output = new StringBuilder();
XmlWriter writer = XmlWriter.Create(output,
new XmlWriterSettings { OmitXmlDeclaration = true });
serializer.Serialize(writer, example, emptyNamespace);
Console.WriteLine(output.ToString());
}
}
You should be able to just serialize like you usually do, and then use the Root property from the resulting document.
You may need to clear the attributes of the element first.
By the way this is awesome.
I implemented this code to make it easy to work with xml fragments as classes quickly and then you can just replace the node when finished. This makes the transition between code and xml ultra-easy.
First create some extension methods.
public static class SerializableFragmentExtensions
{
public static XElement ToElement(this ISerializableFragment iSerializableFragment)
{
var serializer = new XmlSerializer(iSerializableFragment.GetType());
var emptyNamespace = new XmlSerializerNamespaces();
emptyNamespace.Add(String.Empty, String.Empty);
var output = new StringBuilder();
var writer = XmlWriter.Create(output,
new XmlWriterSettings { OmitXmlDeclaration = true });
serializer.Serialize(writer, iSerializableFragment, emptyNamespace);
return XElement.Parse(output.ToString(), LoadOptions.None);
}
public static T ToObject<T>(this XElement xElement)
{
var serializer = new XmlSerializer(typeof (T));
var reader = xElement.CreateReader();
var obj = (T) serializer.Deserialize(reader);
return obj;
}
}
Next Implement the required interface (marker interface--I know you are not supposed to but I think this is the perfect reason to it.)
public interface ISerializableFragment
{
}
Now all you have to do is decorate any Serializable class, you want to convert to an XElement Fragment, with the interface.
[Serializable]
public class SomeSerializableClass : ISerializableFragment
{
[XmlAttribute]
public string SomeData { get; set; }
}
Finally test the code.
static void Main(string[] args)
{
var someSerializableClassObj = new SomeSerializableClass() {SomeData = "Testing"};
var element = someSerializableClass.ToElement();
var backToSomeSerializableClassObj = element.ToObject<SomeSerializableClass>();
}
Thanks again for this amazingly useful code.

Model to XML file mapping - How to find location of deserialized object in soucre XML File.

Which is the best way to map my model to XML file using c# serializer. I mean that if for example I select an deserialized object I could be able to find the xml source text in XML file.
I got a working sample for you and you can explore further on it.
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication5
{
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public int XMLLine { get; set; }
}
public class Persons : List<Person> { }
class Program
{
static void Main(string[] args)
{
//create your objects
Person p = new Person();
p.Age = 35;
p.Name = "Arnold";
Person p2 = new Person();
p2.Age = 36;
p2.Name = "Tom";
Persons ps = new Persons();
ps.Add(p);
ps.Add(p2);
//Serialize them to XML
XmlSerializer xs = new XmlSerializer(typeof(Persons));
XDocument d = new XDocument();
using (XmlWriter xw = d.CreateWriter())
xs.Serialize(xw, ps);
//print xml
//System.Diagnostics.Debug.WriteLine(d.ToString());
// it will produce following xml. You can save it to file.
//I have saved it to variable xml for demo
string xml = #"<ArrayOfPerson>
<Person>
<Age>35</Age>
<Name>Arnold</Name>
<XMLLine>0</XMLLine>
</Person>
<Person>
<Age>36</Age>
<Name>Tom</Name>
<XMLLine>0</XMLLine>
</Person>
</ArrayOfPerson>";
XDocument xdoc = XDocument.Parse(xml, LoadOptions.SetLineInfo);
// A little trick to get xml line
xdoc.Descendants("Person").All(a => { a.SetElementValue("XMLLine", ((IXmlLineInfo)a).HasLineInfo() ? ((IXmlLineInfo)a).LineNumber : -1); return true; });
//deserialize back to object
Persons pplz = xs.Deserialize((xdoc.CreateReader())) as Persons;
pplz.All(a => { Console.WriteLine(string.Format("Name {0} ,Age{1} ,Line number of object in XML File {2}", a.Name, a.Age, a.XMLLine)); return true; });
Console.ReadLine();
}
}
}
and It will give your results like
Name Arnold ,Age35 ,Line number of object in XML File 2
Name Tom ,Age36 ,Line number of object in XML File 7
You can try this extension method:
public static string ToXml<T>(this object obj)
{
using (var memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
return Encoding.ASCII.GetString(memoryStream.ToArray());
}
}
}
public static void ToXmlFile<T>(this object obj, string fileName)
{
using (TextWriter streamWriter = new StreamWriter(fileName))
{
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(streamWriter, obj);
}
}
USAGE:
// you will get this on a string variable
var xmlString = yourModel.ToXml<YourModel>();
// you will save our object in a file.
yourModel.ToXmlFile<YourModel>(#"C:\yourModelDump.xml");
Please be noted to add SerializableAttribute on your class
[Serializable]
public class YourModel
{
//...
}
This should do it

C# XML to Listbox Help

I have XML that is being returned back from a rest service WCF. The following is an example of the XML
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<catalog version="1.1"><dataset id="354" name="Mariano - Ship Drift" description="Global Currents, Static" datatype="currents" rank="5" saropsrank="4" format="netcdf" starttime="1980-01-01T00:00:00" endtime="2019-01-01T00:00:00" extentleft="-180.0000" extentbottom="-90.0000" extentright="180.0000" extenttop="90.0000" source="STATIC" wmslayeridstr="MARIANO_currents" confidence="L" directionfrom="no" image="ne_ndbc.jpg" />
</catalog>
</string>
I need to get the value from id, name, description, etc... and put it into a list or a listbox.
WebResponse response = restWebRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
Reponse stream is the stream that holds the XML.
Any ideas?
XDocument doc = XDocument.Load(responseStream);
var elem = doc.Descendants().FirstOrDefault(el => el.Name.LocalName == "dataset");
if(elem != null)
{
var attID = elem.Attribute("id");
if(attID != null)
Console.WriteLine(attID.Value);
}
OR
You could directly get the IEnumerable with an anonymous type:
XDocument doc = XDocument.Parse(xml);
var values = doc.Descendants("dataset")
.Select(el => new { id = el.Attribute("id").Value,
name = el.Attribute("name").Value
}
);
Here's another approach: (I tested your XML by loading it from a file.)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
namespace delete4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load();
}
void Load()
{
var stream = new FileStream("c:\\pj\\data.txt", FileMode.Open);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "string";
xRoot.IsNullable = true;
xRoot.Namespace = "http://schemas.microsoft.com/2003/10/Serialization/";
XmlSerializer s = new XmlSerializer(typeof(sstring), xRoot);
var o = s.Deserialize(stream) as sstring; // o is your loaded object
stream.Close();
}
[ XmlRoot("string"), XmlType("string")]
public class sstring
{
public Catalog catalog;
}
public class Catalog
{
public Dataset dataset;
}
public class Dataset
{
[XmlAttribute("name")]
public string Name;
[XmlAttribute("id")]
public string ID;
[XmlAttribute("description")]
public string Description;
}
}
}

Categories

Resources