list inside list - c#

I know its a lot code... sorry for that....my list class is like this..
public class XMLList
{
public string Title { get; set; }
[DataMember]
public string Link { get; set; }
[DataMember]
public DateTime pubDate { get; set; }
[DataMember]
public string dcCreator { get; set; }
[DataMember]
public string GUID { get; set; }
[DataMember]
public Int32 wpPostId { get; set; }
[DataMember]
public string wpStatus { get; set; }
[DataMember]
public Int32 wpMenuOrd { get; set; }
[DataMember]
public string Category { get; set; }
[DataMember]
public List<Comment> Comments { get; set; }
}
public class Comment
{
[DataMember]
public Int32 wpCmtId { get; set; }
[DataMember]
public string wpCmtAuthor { get; set; }
[DataMember]
public string wpCmtAuthorEmail { get; set; }
[DataMember]
public string wpCmtAuthorURL { get; set; }
[DataMember]
public Int64 wpCmtAuthorIP { get; set; }
[DataMember]
public DateTime wpCmtAuthorDate { get; set; }
}
my c# code is like this
XmlDocument doc = new XmlDocument();
doc.Load(#"xml\willowcreekassociationblog.wordpress.xml");
//Get Channel Node
XmlNode channelNode = doc.SelectSingleNode("rss/channel");
if (channelNode != null)
{
//Add NameSpace
XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
nameSpace.AddNamespace("excerpt", "http://wordpress.org/export/1.2/excerpt/");
nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
nameSpace.AddNamespace("wfw", "http://wellformedweb.org/CommentAPI/");
nameSpace.AddNamespace("wp", "http://wordpress.org/export/1.2/");
//Parse each item
foreach (XmlNode itemNode in channelNode.SelectNodes("item"))
{
objrssItem.Add(rssItem);
rssItem.GUID = itemNode.SelectSingleNode("guid").InnerText;
rssItem.Title = itemNode.SelectSingleNode("title").InnerText;
rssItem.dcCreator = itemNode.SelectSingleNode("dc:creator", nameSpace).InnerText;
rssItem.Link = itemNode.SelectSingleNode("link").InnerText;
rssItem.pubDate = DateTime.Parse(itemNode.SelectSingleNode("pubDate").InnerText);
rssItem.ContentEncoded = itemNode.SelectSingleNode("content:encoded", nameSpace).InnerText;
XmlNode cNode = doc.SelectSingleNode("rss/channel/item");
foreach (XmlNode commentNode in cNode.SelectNodes("wp:comment", nameSpace))
{
//rssItem.Comments = Comments
rsscomment.wpCmtId = Convert.ToInt32(commentNode.SelectSingleNode("wp:comment_id", nameSpace).InnerText);
rsscomment.wpCmtAuthor = commentNode.SelectSingleNode("wp:comment_author", nameSpace).InnerText;
rsscomment.wpCmtContent = commentNode.SelectSingleNode("wp:comment_content", nameSpace).InnerText;
}
}
oXMLListResult.listOfXMLResult = objrssItem;
}
i have xml like enter link description here
when I am trying to read for each item in channel with xmlnode and its working fine. and each item has multiple comments which trying to achieve by using foreach inside foreach. But wp:comment foreach item its not working. What am i doing wrong? I did some google but no luck.
Thanks.

XmlNode cNode = doc.SelectSingleNode("rss/channel/item");
This is resetting your item enumeration to the beginning, which would cause every item to have identical comments.
EDIT:
I believe this is the easiest way to fix the problem I mentioned. By searching below the already selected node, you avoid the repetition. Note that cNode is no longer required.
foreach (XmlNode commentNode in itemNode.SelectNodes("wp:comment", nameSpace))

Related

merging two multi level class objects with element update c#

I have two objects (A,B) of same class type (PPLWebOperatorGridList). I need update the A.OldValue with B.Value.
I have tried by adding the guid property and update it in the constructor as shown below. But these object list may repeat same value:
public PPLWebOperatorGridList()
{
this.guid = this.FieldName+this.TagName+
this.Length+this.Encoder+this.Value;
}
public string guid { get; set; }
I have tried as below. I know there are bugs in it but consider the idea in it.
private List<PPLWebOperatorGridList> UpddateOldValues(List<PPLWebOperatorGridList> customeTlvList, List<PPLWebOperatorGridList> customeTlvList2)
{
foreach (var list in customeTlvList)
{
foreach (var list1 in customeTlvList2)
{
if (list.guid == list1.guid)
{
list.OldValue = list1.Value;
if (list.children.Count > 0)
UpddateOldValues(list.children.ToList(), list1.children.ToList());
}
}
}
return customeTlvList;
}
The guid property may be same for some in the list.
class PPLWebOperatorGridList
{
public bool expanded { get; set; }
public string FieldName { get; set; }
public string TagName { get; set; }
public string Length { get; set; }
public string Encoder { get; set; }
public string Value { get; set; }
public List<PPLWebOperatorGridList> children { get; set; }
public string OldValue { get; set; }
}
I need to loop through based on index and update the A.OldValue with B.Value. I am not very familiar with linq, so please suggest a solution.

Why an XML string cannot be deserialized due to prefixes in root elements?

I have the XML below:
<y:input xmlns:y='http://www.blahblah.com/engine/42'>
<y:datas>
<y:instance yclass='ReportPeriod' yid="report">
<language yid='en'/>
<threshold>0.6</threshold>
<typePeriod>predefinedPeriod</typePeriod>
<interval>month</interval>
<valuePeriod>April</valuePeriod>
<fund yclass="Fund">
<name>K</name>
<indexName>CAC40</indexName>
</fund>
</y:instance>
</y:datas>
</y:input>
That I am trying to deserialize to
[XmlRoot(ElementName="fund")]
public class Fund
{
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="indexName")]
public string IndexName { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
}
[XmlRoot(ElementName="instance", Namespace="http://www.blahblah.com/engine/42")]
public class Instance
{
[XmlElement(ElementName="language")]
public Language Language { get; set; }
[XmlElement(ElementName="threshold")]
public string Threshold { get; set; }
[XmlElement(ElementName="typePeriod")]
public string TypePeriod { get; set; }
[XmlElement(ElementName="interval")]
public string Interval { get; set; }
[XmlElement(ElementName="valuePeriod")]
public string ValuePeriod { get; set; }
[XmlElement(ElementName="fund")]
public Fund Fund { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
[XmlAttribute(AttributeName="yid")]
public string Yid { get; set; }
}
[XmlRoot(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public class Datas
{
[XmlElement(ElementName="instance", Namespace="http://www.blahblah.com/engine/42")]
public Instance Instance { get; set; }
}
[XmlRoot(ElementName="input", Namespace="http://www.blahblah.com/engine/42")]
public class Input
{
[XmlElement(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public Datas Datas { get; set; }
[XmlAttribute(AttributeName="y", Namespace="http://www.blahblah.com/engine/42", Form = XmlSchemaForm.Qualified)]
public string Y { get; set; }
}
However, when deserializing the XML above:
public static class Program
{
public static void Main(params string[] args)
{
var serializer = new XmlSerializer(typeof(Input));
using (var stringReader = new StringReader(File.ReadAllText("file.xml")))
{
using(var xmlReader = XmlReader.Create(stringReader))
{
var instance = (Input)serializer.Deserialize(stringReader);
}
}
}
}
I get an error due to the y prefix...
There is an error in XML document (1, 1). ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
Reading some posts like that one: https://stackoverflow.com/a/36163079/4636721 it seems that there is maybe a bug with the XmlSerializer.
The cause of the exception is that you are passing stringReader rather than xmlReader to serializer.Deserialize(). You should be passing the XML reader instead:
Input instance = null;
var serializer = new XmlSerializer(typeof(Input));
using (var stringReader = new StreamReader("file.xml"))
{
using(var xmlReader = XmlReader.Create(stringReader))
{
instance = (Input)serializer.Deserialize(xmlReader);
}
}
(Apparently XmlReader.Create(stringReader) advances the text reader a bit, so if you later attempt to read from the stringReader directly, it has been moved past the root element.)
You also have some errors in your data model. It should look like:
[XmlRoot(ElementName="fund")]
public class Fund
{
[XmlElement(ElementName="name")]
public string Name { get; set; }
[XmlElement(ElementName="indexName")]
public string IndexName { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
}
[XmlRoot(ElementName="instance")]
[XmlType(Namespace = "")] // Add this
public class Instance
{
[XmlElement(ElementName="language")]
public Language Language { get; set; }
[XmlElement(ElementName="threshold")]
public string Threshold { get; set; }
[XmlElement(ElementName="typePeriod")]
public string TypePeriod { get; set; }
[XmlElement(ElementName="interval")]
public string Interval { get; set; }
[XmlElement(ElementName="valuePeriod")]
public string ValuePeriod { get; set; }
[XmlElement(ElementName="fund")]
public Fund Fund { get; set; }
[XmlAttribute(AttributeName="yclass")]
public string Yclass { get; set; }
[XmlAttribute(AttributeName="yid")]
public string Yid { get; set; }
}
[XmlRoot(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public class Datas
{
[XmlElement(ElementName="instance", Namespace="http://www.blahblah.com/engine/42")]
public Instance Instance { get; set; }
}
[XmlRoot(ElementName="input", Namespace="http://www.blahblah.com/engine/42")]
public class Input
{
[XmlElement(ElementName="datas", Namespace="http://www.blahblah.com/engine/42")]
public Datas Datas { get; set; }
//Remove This
//[XmlAttribute(AttributeName="y", Namespace="http://www.blahblah.com/engine/42", Form = XmlSchemaForm.Qualified)]
//public string Y { get; set; }
}
// Add this
[XmlRoot(ElementName="language")]
public class Language
{
[XmlAttribute(AttributeName="yid")]
public string Yid { get; set; }
}
Notes:
xmlns:y='http://www.blahblah.com/engine/42' is an XML namespace declaration and thus should not be mapped to a member in the data model.
The child elements of <y:instance ...> are not in any namespace. Unless the namespace of the child elements is specified by attributes somehow, XmlSerializer will assume that they should be in the same namespace as the containing element, here http://www.blahblah.com/engine/42".
Thus it is necessary to add [XmlType(Namespace = "")] to Instance to indicate the correct namespace for all child elements created from Instance. (Another option would be to add [XmlElement(Form = XmlSchemaForm.Unqualified)] to each member, but I think it is easier to set a single attribute on the type.)
A definition for Language is not included in your question, so I included one.
It will be more efficient to deserialize directly from your file using a StreamReader than to read first into a string, then deserialize from the string using a StringReader.
Working sample fiddle here.

Parse XML string with LINQ, create new object from xml

Given the following requirements and code, I have not yet found ONE answer that actually works.
I have an XML field in a SQL Server Database table. Why is it in there? I have no idea. I didn't put it in there. I just have to get the data out and into a List that I can combine with another List to populate a grid in a WPF app that has an MVVM architecture.
Here is that List:
List QAItems = new List();
The QADailyXValueCalCheck type is as follows:
using System.Xml.Serialization;
namespace ConvertXmlToList {
[XmlRoot(ElementName = "column")]
public class QADailyXValueCalCheck {
[XmlElement]
public string Regs { get; set; }
[XmlElement]
public string BasisTStamp { get; set; }
[XmlElement]
public string DAsWriteTStamp { get; set; }
[XmlElement]
public string InjEndTime { get; set; }
[XmlElement]
public bool Manual { get; set; }
[XmlElement]
public decimal RefValue { get; set; }
[XmlElement]
public decimal MeasValue { get; set; }
[XmlElement]
public string Online { get; set; }
[XmlElement]
public decimal AllowableDrift { get; set; }
[XmlElement]
public bool FailOoc { get; set; } = false;
[XmlElement]
public bool FailAbove { get; set; }
[XmlElement]
public bool FailBelow { get; set; }
[XmlElement]
public bool FailOoc5Day { get; set; }
[XmlElement]
public decimal InstSpan { get; set; }
[XmlElement]
public decimal GasLevel { get; set; }
[XmlElement]
public string CId { get; set; }
[XmlElement]
public string MId { get; set; }
[XmlElement]
public string CylinderId { get; set; }
[XmlElement]
public string CylinderExpDate { get; set; }
[XmlElement]
public string CylinderVendorId { get; set; }
[XmlElement]
public string CylinderGasTypeCode { get; set; }
}
}
The XML is being stored in a string, xmlString and comes out of the db in the following form:
<Regs>40CFR75</Regs>
<BasisTStamp>2016-02-15 05:18</BasisTStamp>
<DASWriteTStamp>2016-02-15 05:40</DASWriteTStamp>
<InjEndTime>2016-02-15 05:23</InjEndTime>
<Manual>0</Manual>
<RefValue>169.7</RefValue>
<MeasValue>169.27</MeasValue>
<Online>14</Online>
<AllowableDrift>15</AllowableDrift>
<FailAbove>0</FailAbove>
<FailBelow>0</FailBelow>
<InstSpan>300</InstSpan>
<GasLevel>MID</GasLevel>
<CID>111</CID>
<MID>N10</MID>
<CylinderID>CC357464</CylinderID>
<CylinderExpDate>2022-08-12</CylinderExpDate>
<CylinderVendorID>B22014</CylinderVendorID>
<CylinderGasTypeCode>BALN,SO2,NO,CO2</CylinderGasTypeCode>
Now, in order to get past the XML API's problem with "rootless" xml, I've added a root:
xmlString = "<columns>" + xmlString + "</columns>";
To parse this, I use:
XDocument doc = XDocument.Parse(xmlString);
Finally, to attempt to extract the VALUES from the XML and populate an instance of QADailyXValueCalCheck, I have the following code - which was adapted to work from other examples - THAT DO NOT WORK.
var xfields =
from r in doc.Elements("columns")
select new QADailyXValueCalCheck
{
Regs = (string) r.Element("Regs"),
BasisTStamp = (string) r.Element("BasisTStamp"),
DAsWriteTStamp = (string) r.Element("DASWriteTStamp"),
InjEndTime = (string) r.Element("InjEndTime"),
Manual = (bool) r.Element("Manual"),
RefValue = (decimal) r.Element("RefValue"),
MeasValue = (decimal)r.Element("MeasValue"),
Online = (string)r.Element("Online"),
AllowableDrift = (decimal)r.Element("AllowableDrift"),
//FailOoc = (bool)r.Element("FailOoc"),
//FailAbove = (bool)r.Element("FailAbove"),
//FailBelow = (bool)r.Element("FailBelow"),
//FailOoc5Day = (bool)r.Element("FailOoc5Day"),
//InstSpan = (decimal)r.Element("InstSpan"),
//GasLevel = (decimal)r.Element("GasLevel"),
CId = (string)r.Element("CID"),
MId = (string)r.Element("MID"),
CylinderId = (string)r.Element("CylinderId"),
CylinderExpDate = (string)r.Element("CylinderExpDate"),
CylinderVendorId = (string)r.Element("CylinderVendorId"),
CylinderGasTypeCode = (string)r.Element("CylinderGasTypeCode")
};
The code immediately above does NOT create a new instance of the class, "QADailyXValueCalCheck" which can be added to the List. I have a few null values that are causing a problem with that code, but that is a separate issue that I will deal with another time.
For now, can anyone tell me how that "var xfields = " query instantiates a new QADailyXValueCalCheck object that can be added to my List of the same type?
What code is missing? Thank you to the LINQ/XML genius that can answer this.
I had a similar question on XML parsing the other day from someone else here:
Create a List from XElements Dynamically
I think in the end you would be better served using a class with xml adornments and then have extension classes that serialize or deserialize the data. This makes it better IMHO in two ways:
1. You don't have to rewrite the parser and the POCO class, just the POCO class.
2. You can be free to reuse the extension method in other places.
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace GenericTesting.Models
{
[XmlRoot(ElementName = "column")]
public class QADailyXValueCalCheck
{
[XmlElement]
public string Regs { get; set; }
[XmlElement]
public string BasisTStamp { get; set; }
[XmlElement]
public string DAsWriteTStamp { get; set; }
[XmlElement]
public string InjEndTime { get; set; }
[XmlElement]
public int Manual { get; set; }
[XmlElement]
public decimal RefValue { get; set; }
[XmlElement]
public decimal MeasValue { get; set; }
[XmlElement]
public int Online { get; set; }
[XmlElement]
public decimal AllowableDrift { get; set; }
[XmlElement]
public bool FailOoc { get; set; } = false;
[XmlElement]
public int FailAbove { get; set; }
[XmlElement]
public int FailBelow { get; set; }
[XmlElement]
public bool FailOoc5Day { get; set; }
[XmlElement]
public decimal InstSpan { get; set; }
[XmlElement]
public string GasLevel { get; set; }
[XmlElement]
public string CId { get; set; }
[XmlElement]
public string MId { get; set; }
[XmlElement]
public string CylinderId { get; set; }
[XmlElement]
public string CylinderExpDate { get; set; }
[XmlElement]
public string CylinderVendorId { get; set; }
[XmlElement]
public string CylinderGasTypeCode { get; set; }
}
}
And for the purpose of serializing/deserializing let me give extension methods for those:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace GenericTesting
{
static class ExtensionHelper
{
public static string SerializeToXml<T>(this T valueToSerialize)
{
dynamic ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringWriter sw = new StringWriter();
using (XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
dynamic xmler = new XmlSerializer(valueToSerialize.GetType());
xmler.Serialize(writer, valueToSerialize, ns);
}
return sw.ToString();
}
public static T DeserializeXml<T>(this string xmlToDeserialize)
{
dynamic serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlToDeserialize))
{
return (T)serializer.Deserialize(reader);
}
}
}
}
And a simple main entry point in a console app:
static void Main(string[] args)
{
var thingie = new QADailyXValueCalCheck
{
Regs = "40CFR75",
BasisTStamp = "2016-02-15 05:18",
DAsWriteTStamp = "2016-02-15 05:40",
InjEndTime = "2016-02-15 05:23",
Manual = 0, //Boolean This will probably mess up Changed to Int
RefValue = 169.7M,
MeasValue = 169.27M,
Online = 14, //Mismatch Type? Change to Int
AllowableDrift = 15,
FailAbove = 0, //Boolean This will probably mess up Changed to Int
FailBelow = 0, //Boolean This will probably mess up Changed to Int
InstSpan = 300,
GasLevel = "MID", //This is marked as a decimal? Changed to string
CId = "111",
MId = "N10",
CylinderId= "CC357464",
CylinderExpDate ="2022-08-12",
CylinderVendorId = "B22014",
CylinderGasTypeCode = "BALN,SO2,NO,CO2"
};
var serialized = thingie.SerializeToXml();
var deserialized = serialized.DeserializeXml<QADailyXValueCalCheck>();
Console.ReadLine();
}
This serializes just like this and I can get it back to deserialized as well.

deserialize list of XElement without list root member

In my case I've a XMLTAG <phrase> that can contains one or more XMLTAG <q> but they can appear in phraseTag value in a random order.
Here it is an example of xmlcode:
<phrase level="1">
Where
<q>are</q>
<subject>you</subject>
<q>going?</q>
</phrase>
For deserialization I'm using this class:
[XmlRoot("phrase")]
public class Phrase
{
public Phrase()
{
this.Quoted = new List<string>();
}
[XmlAttribute("level")]
public int Level { get; set; }
[XmlElement("subject")]
public string Subject { get; set; }
[XmlText]
public string Value { get; set; }
[XmlElement("q")]
List<string> Quoted { get; set; }
}
My extension method is:
public static T Deserialize<T>(this XElement xElement)
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(xElement.CreateReader());
}
catch (Exception)
{
throw;
}
}
When I deserialize XML document all class members are successfully serialized:
Phrase.Level = 1
Phrase.Subyect = "you"
Phrase.Value = "Where"
How can I deserialize <q> tags?
I've tried to use XmlArrayAttibute and XmlArrayItemAttibute but I have not a member for this list (eg. QTags).
You need XmlElement attribute :)
[XmlRoot("phrase")]
public class Phrase
{
[XmlElement("q")]
public List<string> q { get; set; }
[XmlAttribute("level")]
public int Level { get; set; }
[XmlElement("subject")]
public string Subject { get; set; }
[XmlText]
public string Value { get; set; }
}

Nested XML deserialization to c# gives null values

I have searched alot to find a solution, but couldn't come up with one after all.
So I hope that someone here can help me out.
I have an xml structure:
<?xml version="1.0" encoding="utf-8" ?>
<ReleaseNoteConfig>
<ReleaseNoteProperties>
<TemplateLocation>Path to the template location</TemplateLocation>
<TemplateFileName>wordfile.docx</TemplateFileName>
<OutLocation>Path to the outlocation</OutLocation>
<ReleaseName>Stackoverflow</ReleaseName>
<ChangeOrder>1234</ChangeOrder>
<ChangesHeader>Change ID</ChangesHeader>
<ProblemsHeader>Problem ID</ProblemsHeader>
<Environment>Test</Environment>
</ReleaseNoteProperties>
<DocProperties>
<AuthorReleaseNote>Vincent Verweij</AuthorReleaseNote>
<CustomerResponsible>Customer name</CustomerResponsible>
<PlannedTestInstallDate>-</PlannedTestInstallDate>
<PlannedAccInstallDate>30/04/2014</PlannedAccInstallDate>
<PlannedProdInstallDate>07/05/2014</PlannedProdInstallDate>
<TestInstallDate>-</TestInstallDate>
<AccInstallDate>-</AccInstallDate>
<ProdInstallDate>-</ProdInstallDate>
<TestInstaller>-</TestInstaller>
<AccInstaller>-</AccInstaller>
<ProdInstaller>-</ProdInstaller>
<UrlProjectPortal>Url to project site</UrlProjectPortal>
</DocProperties>
<SpecialProperties>
<Customer_x0020_Name>Customer company name</Customer_x0020_Name>
<Customer_x0020_Reference>No reference</Customer_x0020_Reference>
<Approval_x0020_Date>15/04/2014</Approval_x0020_Date>
<MyFerranti_x0020_Reference>1234</MyFerranti_x0020_Reference>
<Project_x0020_ID>Proj000001</Project_x0020_ID>
</SpecialProperties>
</ReleaseNoteConfig>
I have used an online generator to create a json from my XML and then json2csharp to obtain the classes that I need. So eventually it came up with this c# code:
public class ReleaseNoteProperties
{
public string TemplateLocation { get; set; }
public string TemplateFileName { get; set; }
public string OutLocation { get; set; }
public string ReleaseName { get; set; }
public string ChangeOrder { get; set; }
public string ChangesHeader { get; set; }
public string ProblemsHeader { get; set; }
public string Environment { get; set; }
}
public class DocProperties
{
public string AuthorReleaseNote { get; set; }
public string CustomerResponsible { get; set; }
public string PlannedTestInstallDate { get; set; }
public string PlannedAccInstallDate { get; set; }
public string PlannedProdInstallDate { get; set; }
public string TestInstallDate { get; set; }
public string AccInstallDate { get; set; }
public string ProdInstallDate { get; set; }
public string TestInstaller { get; set; }
public string AccInstaller { get; set; }
public string ProdInstaller { get; set; }
public string UrlProjectPortal { get; set; }
}
public class SpecialProperties
{
public string Customer_x0020_Name { get; set; }
public string Customer_x0020_Reference { get; set; }
public string Approval_x0020_Date { get; set; }
public string MyFerranti_x0020_Reference { get; set; }
public string Project_x0020_ID { get; set; }
}
public class ReleaseNoteConfig
{
public ReleaseNoteProperties ReleaseNoteProperties { get; set; }
public DocProperties DocProperties { get; set; }
public SpecialProperties SpecialProperties { get; set; }
}
This code will read my XML file and deserializes the XML to the objects.
public ReleaseNoteConfig ReadXmlToObject(string xmlPath)
{
StringReader stream = null;
XmlTextReader reader = null;
var xDocument = XDocument.Load(xmlPath);
string xml = xDocument.ToString();
try
{
// Serialise the object
XmlSerializer serializer = new XmlSerializer(typeof(ReleaseNoteConfig));
// Read the XML data
stream = new StringReader(xml);
// Create a reader
reader = new XmlTextReader(stream);
// Convert reader to an object
return (ReleaseNoteConfig)serializer.Deserialize(reader);
}
catch
{
return null;
}
finally
{
if (stream != null) stream.Close();
if (reader != null) reader.Close();
}
}
Now the problem; when I debug in Visual Studio, I see that two of the three objects are filled. Here is a screenshot that I took from the debugger:
http://www.smartus.be/xmlProblem/debugger.png
As you can see, DocProperties and ReleaseNoteProperties are filled correctly but SpecialProperties has all null values. First I thought it had something to do with the underscores, but when I added an underscore to a property in DocProperties it was also filled correctly.
I also tried adding the attributes above the properties like XmlElement, XmlRoot etc. but that didn't help either.
I also double checked for typos but it seems that there are none...
Hopefully you guys can help me out on this one.
Thanks in advance.
Vincent
Change your SpecialProperties class to this:
public class SpecialProperties
{
[XmlElement("Customer Name")]
public string CustomerName { get; set; }
[XmlElement("Customer Reference")]
public string CustomerReference { get; set; }
[XmlElement("Approval Date")]
public string ApprovalDate { get; set; }
[XmlElement("MyFerranti Reference")]
public string MyFerrantiReference { get; set; }
[XmlElement("Project ID")]
public string ProjectID { get; set; }
}
You can change the property names if you want, the important parts are the XmlElement attributes.
I have checked your code.
Can you Remove the underscores in the "Customer_x0020_Name" ? at the same time you need to change the property names in the class.
Its going to work.
Will this suggestions helps you?
i have checked it .. its working.
I am not sure , whether the tag name with underscore is legal or not.
Mark the answer , if it has solved you question

Categories

Resources