Deserialization XML, XMLElement, XMLAttribute
XML:
<PET>
<RES>Correct</RES>
<PC version="1.1">
<MESSAGE conf="1">SMS</DESC>
<URL>www.google.com</URL>
</PC>
<PRU>200</PRU>
</PET>
Class:
[XmlRoot("PET")]
public class Prueba
{
[XmlElement("RES")]
public string Res { get; set; }
[XmlElement("PRU")]
public string Pru { get; set; }
//PC Attribute
//MESSAGE element AND Attribute
//URL element
}
Method:
public void Prueba()
{
Prueba p = new Prueba();
XmlSerializer serializer = new XmlSerializer(p.GetType());
using (StreamReader reader = new StreamReader("Repositories/Local/Prueba.xml"))
{
p = (Prueba)serializer.Deserialize(reader);
}
}
How to read the attribute <PC>, and MESSAGE element (attribute too) and URL?
Add
[XmlElement("PC")]
public PC pc { get; set; }
And create class for PC ,
[XmlRoot("PET")]
public class PC
{
[XmlElement("MESSAGE")]
public string MES { get; set; }
[XmlElement("URL")]
public string url { get; set; }
}
Related
I have an XML file that I am parsing through and have come across a specific element that has it's own child nodes. The XML file is below:
<status.AppleSettings>
<AppleInstance MaxCost="250" Status="77" NewMode="5" SharePrice="350"
FlagTF="False" TimeClock="0" TimeClockSec="14"
Options="7532890" ID="JK_7755" Owner="SLP90"
Server="PA.SL90.COL" Name="SLP90" GroupName="COL.PA"
Instance="AppleServiceInstance" NewFlag="True" FinalCount="0"/>
<AppleInstance MaxCost="5" Status="0" NewMode="1" SharePrice="0"
FlagTF="False" TimeClock="300" TimeClockSec="1000"
Options="56794577431" Owner="A.CON" Instance="SL91"
NewFlag="True" FinalCount="1" List="1450, 1430"
Keyrepo="SYSTEMSERVER_7671902"/>
</status.AppleSettings>
As you can see, there's a parent node - AppleSettings and then two child nodes w/ the same name - AppleInstance. I created two separate classes for the child nodes since they have different attributes. I am able to access AppleSettings and when I do a quickwatch I can see the two child nodes inside, I just can't figure out how to access them. New to XML parsing and C# so everything is trial and error, learning a lot from stackoverflow.
Here is the code I have to access the AppleSettings parent node:
private List<Data> GetAppleSettingsNode(List<XmlDocument> XMLdocument, List<Data> DataList)
{
for (int i = 0; i < XMLdocument.Count(); i++)
{
AppleSettings temp = new AppleSettings();
var temp2 = XMLdocument[i].DocumentElement.SelectNodes("//AppleSettings");
foreach (var node in temp2)
{
var temp3 = node.ToString();
}
XmlNode xmlNode1 = XMLdocument[i].SelectSingleNode("//AppleSettings");
XmlSerializer serial1 = new XmlSerializer(typeof(AppleSettings));
temp = (AppleSettings)serial1.Deserialize(new XmlNodeReader(xmlNode1));
}
}
Is it even necessry to access the AppleSettings node? Could I go directly to the two AppleInstance child nodes? If someone could help me out, I'd appreciate it. Thanks!
It is better to use LINQ to XML API.
(1) The code below shows how to access any XML attribute by its name.
(2) .FirstOrDefault()?.Value technique will prevent exceptions generation when an attribute is missing.
c#
void Main()
{
const string FILENAME = #"e:\Temp\AppleSettings.xml";
XDocument doc = XDocument.Load(FILENAME);
foreach (var el in doc.Descendants("AppleInstance"))
{
Console.WriteLine("MaxCost={0}", el.Attributes("MaxCost").FirstOrDefault()?.Value);
Console.WriteLine("Instance={0}", el.Attributes("Instance").FirstOrDefault()?.Value);
Console.WriteLine("GroupName={0}", el.Attributes("GroupName").FirstOrDefault()?.Value);
}
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication8
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
Root root = (Root)serializer.Deserialize(reader);
}
}
public class Root
{
[XmlArray("status.AppleSettings")]
[XmlArrayItem("AppleInstance")]
public List<ApppleInstance> AppleInstances { get; set; }
}
public class ApppleInstance
{
[XmlAttribute()]
public int MaxCost { get; set; }
[XmlAttribute()]
public int Status { get; set; }
[XmlAttribute()]
public int NewMode { get; set; }
[XmlAttribute()]
public int SharePrice { get; set; }
private Boolean _FlagTF { get; set; }
[XmlAttribute()]
public string FlagTF
{
get { return _FlagTF? "True" : "False";}
set { _FlagTF = (value == "True") ? true : false;}
}
[XmlAttribute()]
public int TimeClock { get; set; }
[XmlAttribute()]
public int TimeClockSec { get; set; }
[XmlAttribute()]
public long Options { get; set; }
[XmlAttribute()]
public string ID { get; set; }
[XmlAttribute()]
public string Owner { get; set; }
[XmlAttribute()]
public string Server { get; set; }
[XmlAttribute()]
public string Name { get; set; }
[XmlAttribute()]
public string GroupName { get; set; }
[XmlAttribute()]
public string Instance { get; set; }
private Boolean _NewFlag { get; set; }
[XmlAttribute()]
public string NewFlag
{
get { return _NewFlag ? "True" : "False"; }
set { _NewFlag = (value == "True") ? true : false; }
}
[XmlAttribute()]
public int FinalCount { get; set; }
private int[] _List { get; set; }
[XmlAttribute()]
public string List
{
get { return string.Join(",",_List);}
set { _List = value.Split(new char[] {','}).Select(x => int.Parse(x)).ToArray() ;}
}
[XmlAttribute()]
public string Keyrepo { get; set; }
}
}
The i of LargeXMLResponse[i] is loop count of the Large XML response if your response tag in wrapped up in between, and if you have a alternative way please go ahead with.
var ResponseToList = LargeXMLResponse[i].Descendants("Response").ToList();
if (ResponseToList.Count() > 0){
for (var pf = 0; pf < ResponseToList.Count(); pf++)
{
ResponseInfoList.Add(new ResponseToList{
id = ResponseToList[pf].Descendants("Block").Attributes("id").Count() > 0 ?
ResponseToList[pf].Descendants("Block ").Attributes("id").First().Value : "",
});
}
}
I see this question often enough, but nobody's title really seems to depict their question. I get a large response object back from a Web API that contains general response information, along with the data object I want to deserialize.
Full XML:
<?xml version="1.0"?>
<root>
<status>
<apiErrorCode>0</apiErrorCode>
<apiErrorMessage/>
<dbErrorCode>0</dbErrorCode>
<dbErrorMessage/>
<dbErrorList/>
</status>
<data>
<modelName>ReportXDTO</modelName>
<modelData>
<id>1780</id>
<reportTitle>Access Level (select) with Door Assignment</reportTitle>
<hasParameters>true</hasParameters>
<parameters>
<dataType>STRING</dataType>
<title>Access Level:</title>
<index>1</index>
<allowMulti>true</allowMulti>
<selectSql>SELECT DISTINCT [Name] FROM dbo.[Levels] WHERE [PrecisionFlag] = '0' ORDER BY [Name] </selectSql>
<values>
<value>Door 1</value>
<used>1</used>
</values>
<values>
<value>Door 2</value>
<used>1</used>
</values>
<values>
<value>Door 3</value>
<used>1</used>
</values>
</parameters>
<sourceSql>SELECT [Name], [SData] FROM [Schedules]</sourceSql>
<report/>
</modelData>
<itemReturned>1</itemReturned>
<itemTotal>1</itemTotal>
</data>
<listInfo>
<pageIdRequested>1</pageIdRequested>
<pageIdCurrent>1</pageIdCurrent>
<pageIdFirst>1</pageIdFirst>
<pageIdPrev>1</pageIdPrev>
<pageIdNext>1</pageIdNext>
<pageIdLast>1</pageIdLast>
<itemRequested>1</itemRequested>
<itemReturned>1</itemReturned>
<itemStart>1</itemStart>
<itemEnd>1</itemEnd>
<itemTotal>1</itemTotal>
</listInfo>
</root>
I only want to deserialize the modelData element. The modelData object type is dynamic, depending on the API call.
I deserialize xml in other applications, and created the following method, but don't know how to specifically ONLY get the modelData element:
public static T ConvertXmltoClass<T>(HttpResponseMessage http, string elementName) where T : new()
{
var newClass = new T();
try
{
var doc = JsonConvert.DeserializeXmlNode(http.Content.ReadAsStringAsync().Result, "root");
XmlReader reader = new XmlNodeReader(doc);
reader.ReadToFollowing(elementName);
//The xml needs to show the proper object name
var xml = reader.ReadOuterXml().Replace(elementName, newClass.GetType().Name);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
var serializer = new XmlSerializer(typeof(T));
newClass = (T)serializer.Deserialize(stream);
}
}
catch (Exception e)
{
AppLog.LogException(System.Reflection.MethodBase.GetCurrentMethod().Name, e);
}
return newClass;
}
I have updated this thread multiple times now, to stay current. I started updating it with the first solution. But that solution by itself didn't solve the problem. With the code how it is right now, I get no exceptions, but don't get the xml deserialized to my object. Instead I get a new, blank object. Thoughts?
THOUGH the object type can change, here is my current object I am dealing with: (PLEASE NOTE, that I deserialize the exact xml in modelData, in the Web API)
namespace WebApiCommon.DataObjects
{
[Serializable]
public class ReportXDto
{
public ReportXDto()
{
Parameters = new List<ReportParameterXDto>();
}
public int Id { get; set; }
public string ReportTitle { get; set; }
public bool HasParameters { get; set; } = false;
public List<ReportParameterXDto> Parameters { get; set; }
public string SourceSql { get; set; }
public DataTable Report { get; set; }
}
[Serializable]
public class ReportXDto
{
public ReportXDto()
{
Parameters = new List<ReportParameterXDto>();
}
public int Id { get; set; }
public string ReportTitle { get; set; }
public bool HasParameters { get; set; } = false;
public List<ReportParameterXDto> Parameters { get; set; }
public string SourceSql { get; set; }
public DataTable Report { get; set; }
}
[Serializable]
public class ReportParameterValuesXDto
{
public string Value { get; set; } = "";
public bool Used { get; set; } = false;
}
}
Firstly, XmlSerializer is case sensitive. Thus your property names need to match the XML element names exactly -- unless overridden with an attribute that controls XML serialization such as [XmlElement(ElementName="id")]. To generate a data model with the correct casing I used http://xmltocsharp.azurewebsites.net/ which resulted in:
public class ReportParameterValuesXDto
{
[XmlElement(ElementName="value")]
public string Value { get; set; }
[XmlElement(ElementName="used")]
public string Used { get; set; }
}
public class ReportParametersXDto
{
[XmlElement(ElementName="dataType")]
public string DataType { get; set; }
[XmlElement(ElementName="title")]
public string Title { get; set; }
[XmlElement(ElementName="index")]
public string Index { get; set; }
[XmlElement(ElementName="allowMulti")]
public string AllowMulti { get; set; }
[XmlElement(ElementName="selectSql")]
public string SelectSql { get; set; }
[XmlElement(ElementName="values")]
public List<ReportParameterValuesXDto> Values { get; set; }
}
public class ReportXDto
{
[XmlElement(ElementName="id")]
public string Id { get; set; }
[XmlElement(ElementName="reportTitle")]
public string ReportTitle { get; set; }
[XmlElement(ElementName="hasParameters")]
public string HasParameters { get; set; }
[XmlElement(ElementName="parameters")]
public ReportParametersXDto Parameters { get; set; }
[XmlElement(ElementName="sourceSql")]
public string SourceSql { get; set; }
[XmlElement(ElementName="report")]
public string Report { get; set; }
}
(After generating the model, I modified the class names to match your naming convention.)
Given the correct data model, you can deserialize directly from a selected XmlNode using an XmlNodeReader as shown in How to deserialize a node in a large document using XmlSerializer without having to re-serialize to an intermediate XML string. The following extension method does the trick:
public static partial class XmlExtensions
{
public static IEnumerable<T> DeserializeElements<T>(this XmlNode root, string localName, string namespaceUri)
{
return new XmlNodeReader(root).DeserializeElements<T>(localName, namespaceUri);
}
public static IEnumerable<T> DeserializeElements<T>(this XmlReader reader, string localName, string namespaceUri)
{
var serializer = XmlSerializerFactory.Create(typeof(T), localName, namespaceUri);
while (!reader.EOF)
{
if (!(reader.NodeType == XmlNodeType.Element && reader.LocalName == localName && reader.NamespaceURI == namespaceUri))
reader.ReadToFollowing(localName, namespaceUri);
if (!reader.EOF)
{
yield return (T)serializer.Deserialize(reader);
// Note that the serializer will advance the reader past the end of the node
}
}
}
}
public static class XmlSerializerFactory
{
// To avoid a memory leak the serializer must be cached.
// https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer
// This factory taken from
// https://stackoverflow.com/questions/34128757/wrap-properties-with-cdata-section-xml-serialization-c-sharp/34138648#34138648
readonly static Dictionary<Tuple<Type, string, string>, XmlSerializer> cache;
readonly static object padlock;
static XmlSerializerFactory()
{
padlock = new object();
cache = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
}
public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
{
if (serializedType == null)
throw new ArgumentNullException();
if (rootName == null && rootNamespace == null)
return new XmlSerializer(serializedType);
lock (padlock)
{
XmlSerializer serializer;
var key = Tuple.Create(serializedType, rootName, rootNamespace);
if (!cache.TryGetValue(key, out serializer))
cache[key] = serializer = new XmlSerializer(serializedType, new XmlRootAttribute { ElementName = rootName, Namespace = rootNamespace });
return serializer;
}
}
}
Then you would deserialize as follows:
var modelData = doc.DeserializeElements<ReportXDto>("modelData", "").FirstOrDefault();
Working sample .Net fiddle here.
For Huge xml files always use XmlReader so you do not get an out of memory issue. See code below to get the element as a string :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
//or Create(Stream)
XmlReader reader = XmlReader.Create(FILENAME);
reader.ReadToFollowing("modelData");
if (!reader.EOF)
{
string modelDataStr = reader.ReadOuterXml();
}
}
}
}
So, I have XML like this:
<tileset firstgid="1" name="simple_tiles" tilewidth="32" tileheight="32" tilecount="16" columns="8">
<image source="../Users/mkkek/Pictures/rpg/default_tiles_x.png" width="256" height="64"/>
</tileset>
When I'm at the tileset node, how can I access the image node and its source attribute? My code is as follows:
public void LoadMaps(ContentManager content)
{
Dictionary<string, string> mapsToLoad = InitMapsToLoad();
foreach (KeyValuePair<string, string> mapToLoad in mapsToLoad)
{
Map map = new Map();
map.Name = Path.GetFileNameWithoutExtension(mapToLoad.Value);
reader = XmlReader.Create("Content/" + mapToLoad.Value);
while(reader.Read())
{
if(reader.NodeType == XmlNodeType.Element)
{
switch(reader.Name)
{
case "tileset":
if(!Tilesets.Any(ts => ts.Name == reader.GetAttribute("name")))
{
// handling the image node here
}
break;
}
}
}
}
}
I usually prefer to use LINQ to XML because I find it's API to be much easier to use than XmlReader, a comparison between the technologies here.
If all you need is getting source attribute value from image element this can be achieved easily:
var doc = XDocument.Load("something.xml");
var root = doc.DocumentElement;
var imageElements = root.Elements("image").ToList();
foreach (var imageElement in imageElements)
{
var sourceAttribute = imageElement.Attribute("source");
var sourceValue = sourceAttribute.Value;
//do something with the source value...
}
More about basic queries in LINQ to XML here.
I will suggest to create some classes that represents the Xml structure, something like this :
[XmlRoot(ElementName = "image")]
public class Image
{
[XmlAttribute(AttributeName = "source")]
public string Source { get; set; }
[XmlAttribute(AttributeName = "width")]
public string Width { get; set; }
[XmlAttribute(AttributeName = "height")]
public string Height { get; set; }
}
[XmlRoot(ElementName = "tileset")]
public class Tileset
{
[XmlElement(ElementName = "image")]
public Image Image { get; set; }
[XmlAttribute(AttributeName = "firstgid")]
public string Firstgid { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "tilewidth")]
public string Tilewidth { get; set; }
[XmlAttribute(AttributeName = "tileheight")]
public string Tileheight { get; set; }
[XmlAttribute(AttributeName = "tilecount")]
public string Tilecount { get; set; }
[XmlAttribute(AttributeName = "columns")]
public string Columns { get; set; }
}
Then In some Utility class add the following method:
public static T DeserializeFromXml<T>(string xml)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
var serializer = new XmlSerializer(typeof(T));
T entity;
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
entity = (T)serializer.Deserialize(reader);
}
return entity;
}
Now you will be able to access to the Image object using the following code:
Tileset tileset=DeserializeFromXml<Tileset>(yourXmlContent);
// now you can access the image from the tileset instance 'tileset.Image.Source'
You are almost done. Add this to your code.
// handling the image node here
if (reader.ReadToDescendant("image"))
{
string source = reader.GetAttribute("source");
}
public class MyStuff {
public string Name { get; set; }
public List<Annotation> Annotations { get; set; }
}
public class Annotation {
public string Name { get; set; }
public string Value { get; set; }
}
How do I get the List of Annotations to serialize as a bunch of XML attributes?
var x = new MyStuff {
Name = "Stuff",
Annotations = new [] {
new Annotation { Name = "Note1", Value = "blah" },
new Annotation { Name = "Note2", Value = "blahblah" }
}.ToList()
};
// turns into something like:
<MyStuff Name="Stuff" ann:Note1="blah" ann:Note2="blahblah" />
ann:Note1 is only valid if ann is an xml namespace,
XNamespace ns = "Annotation";
XElement xElem = new XElement("MyStuff", new XAttribute("Name",x.Name));
xElem.Add(x.Annotations
.Select(a => new XAttribute(ns + a.Name, a.Value)));
var xml = xElem.ToString();
OUTPUT:
<MyStuff Name="Stuff" p1:Note1="blah" p1:Note2="blahblah" xmlns:p1="Annotation" />
XmlDocument doc = new XmlDocument(); // Creating an xml document
XmlElement root =doc.CreateElement("rootelement"); doc.AppendChild(root); // Creating and appending the root element
XmlElement annotation = doc.CreateElement("Name");
XmlElement value = doc.CreateElement("Value");
annotation.InnerText = "Annotation Name Here";
value.InnerText = "Value Here";
doc.AppendChild(annotation);
doc.AppendChild(value);
You can narrow all your list and do the same thing in a loop.
What you can do is add the attribute [XmlAttribute] on your properties:
public class Annotation
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string Value { get; set; }
}
And the result will be like this:
<Annotations>
<Annotation Name="Note1" Value="blah" />
<Annotation Name="Note2" Value="blahblah" />
</Annotations>
The IXmlSerializable interface allows you to customize the serialization of any class.
public class MyStuff : IXmlSerializable {
public string Name { get; set; }
public List<Annotation> Annotations { get; set; }
public XmlSchema GetSchema() {
return null;
}
public void ReadXml(XmlReader reader) {
// customized deserialization
// reader.GetAttribute() or whatever
}
public void WriteXml(XmlWriter writer) {
// customized serialization
// writer.WriteAttributeString() or whatever
}
}
Hoping to get some help on this: I am very thankful that a developer shared this XML file with me because it should save me a lot of headache. But he told me I am on my own with how to read it. Basically I am writing a windows store app for a card game. I have a XML that is my list of cards and want to read it into a list. I get no errors, and have read XML into lists before. Any advice would be appreciated.
Here is a snippet of XML:
<?xml version="1.0" encoding="UTF-8"?><carddatabase>
<cards>
<card>
<name>Tundra Kavu</name>
<set picURL="http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=26805&type=card" picURLHq="" picURLSt="">AP</set>
<color>R</color>
<manacost>2R</manacost>
<type>Creature - Kavu</type>
<pt>2/2</pt>
<tablerow>2</tablerow>
<text>{T}: Target land becomes a Plains or an Island until end of turn.</text>
</card>
</cards>
</carddatabase>
Here is my serializer:
public async void readFile()
{
StorageFolder myFolder = ApplicationData.Current.LocalFolder;
StorageFile myFile = await myFolder.CreateFileAsync("cards.xml", CreationCollisionOption.OpenIfExists);
XmlSerializer Serializer = new XmlSerializer(typeof(List<card>), new XmlRootAttribute("carddatabase"));
string XmlString = await FileIO.ReadTextAsync(myFile);
XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(myFile);
var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto, IgnoreWhitespace = true, IgnoreComments = true };
var stringReader = new StringReader(XmlString);
XmlReader reader = XmlReader.Create(stringReader, settings);
List<card> temp = (List<card>)Serializer.Deserialize(reader);
foreach(card x in temp)
{
await tempTable.InsertAsync(x);
}
}
Here is my card class:
public class card
{
public string id { get; set; }
public string name { get; set; }
public string manacost { get; set; }
public string set { get; set; }
public string color { get; set; }
public string tablerow { get; set; }
public string text { get; set; }
public string type { get; set; }
}
You can parse xml with Linq:
XDocument xdoc = XDocument.Load(myFile);
var cards = from c in xdoc.Descendants("card")
select new card() {
name = (string)c.Element("name"),
manacost = (string)c.Element("manacost"),
set = (string)c.Element("set"),
color = (string)c.Element("color"),
tableRow = (string)c.Element("tablerow"),
text = (string)c.Element("text"),
type = (string)c.Element("type")
};
foreach(var card in cards)
await tempTable.InsertAsync(card);
Also Linq allows you to cast values from string to other datatypes, so you can have property int TableRow { get; set; } in your class, which could be parsed as TableRow = (int)c.Element("tablerow") (or int? if tablerow element is not required).
BTW in C# we use CamelCase names for types and properties. So, consider to have type like:
public class Card
{
public string Id { get; set; }
public string Name { get; set; }
public string ManaCost { get; set; }
public string Set { get; set; }
public string Color { get; set; }
public int TableRow { get; set; }
public string Text { get; set; }
public string Type { get; set; }
}