I have a class object:
[XmlRoot(ElementName = "Tag")]
public class Tag
{
[XmlElement(ElementName = "TagId")]
public string TagId { get; set; }
[XmlElement(ElementName = "TagTitle")]
public string TagTitle { get; set; }
}
[XmlRoot(ElementName = "LocTags")]
public class LocTags
{
[XmlElement(ElementName = "Tag")]
public Tag[] Tag { get; set; }
}
[XmlRoot(ElementName = "test")]
public class test
{
[XmlElement(ElementName = "ID")]
public string ID { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "LocTags")]
public LocTags LocTags { get; set; }
}
And I have data already present like this:
test:
id=1
Name="abc"
locTags
tag
tagId=1
tagTitle="xyz"
id=2
name="qwe"
...
I would like to test=1 add new object to Tag, should get result:
test:
id=1
Name="abc"
locTags
tag
tagId=1
tagTitle="xyz"
tagId=2
tagTitle="pqr"
id=2
name="qwe"
...
How do I do that?
Edit
List<Tag> tagNew = test.locTags.Tag.ToList();
tagNew.Add(new Tag
{
TagTitle = "pqr",
TagId = "2"
});
test.locTags.Tag = tagNew;
but the last line gives me error:
Error 10 Cannot implicitly convert type 'System.Collections.Generic.List' to 'Tag[]'
Make Tag[] Tag as List<Tag> and then use test.LocTagXY.Tags.Add(newTag)
If you wish to stay with Arrays, use Pradeep Kumar's test.locTags.Tag = tagNew.ToArray()
Related
I cannot bind my c# model with this kind of xml file. Because there is multiple element with same.
This is a example of my XML File.
<Type>
<Loop LoopId="2100A" Name="MEMBER NAME">
<PER>
<!--Contact Function Code-->
<PER01>IP<!--Insured Party--></PER01>
<PER02 />
<!--Communication Number Qualifier-->
<PER03>HP<!--Home Phone Number--></PER03>
<!--Communication Number-->
<PER04>6235834409</PER04>
</PER>
</Loop>
<Loop LoopId="2100C" Name="MEMBER MAILING ADDRESS">
<NM1>
<!--Entity Identifier Code-->
<NM101>31<!--Postal Mailing Address--></NM101>
<!--Entity Type Qualifier-->
<NM102>1<!--Person--></NM102>
</NM1>
</Loop>
<Loop LoopId="2100G" Name="RESPONSIBLE PERSON">
<PER>
<!--Contact Function Code-->
<PER01>IP<!--Insured Party--></PER01>
<PER02 />
<!--Communication Number Qualifier-->
<PER03>HP<!--Home Phone Number--></PER03>
<!--Communication Number-->
<PER04>6235834409</PER04>
</PER>
<LM>
<!--Contact Function Code-->
<LM01>RP<!--Responsible Person--></LM01>
<LM02 />
</LM>
</Loop>
</Type>
I have use this following code to bind. But Code is not working, cause data binding get confused.
[XmlElement(ElementName = "Loop")]
public L3_L1_MemberName L3_L1_MemberName { get; set; }
[XmlElement(ElementName = "Loop")]
public L3_L2_MemberMailingAddress L3_L2_MemberMailingAddress { get; set; }
[XmlElement(ElementName = "Loop")]
public L3_L3_ResponsiblePerson L3_L3_ResponsiblePerson { get; set; }
based your XML, the model looks like
[XmlRoot(ElementName = "PER")]
public class PER
{
[XmlElement(ElementName = "PER01")]
public string PER01 { get; set; }
[XmlElement(ElementName = "PER02")]
public string PER02 { get; set; }
[XmlElement(ElementName = "PER03")]
public string PER03 { get; set; }
[XmlElement(ElementName = "PER04")]
public string PER04 { get; set; }
}
[XmlRoot(ElementName = "Loop")]
public class Loop
{
[XmlElement(ElementName = "PER")]
public PER PER { get; set; }
[XmlAttribute(AttributeName = "LoopId")]
public string LoopId { get; set; }
[XmlAttribute(AttributeName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "NM1")]
public NM1 NM1 { get; set; }
[XmlElement(ElementName = "LM")]
public LM LM { get; set; }
}
[XmlRoot(ElementName = "NM1")]
public class NM1
{
[XmlElement(ElementName = "NM101")]
public string NM101 { get; set; }
[XmlElement(ElementName = "NM102")]
public string NM102 { get; set; }
}
[XmlRoot(ElementName = "LM")]
public class LM
{
[XmlElement(ElementName = "LM01")]
public string LM01 { get; set; }
[XmlElement(ElementName = "LM02")]
public string LM02 { get; set; }
}
[XmlRoot(ElementName = "Type")]
public class Type
{
[XmlElement(ElementName = "Loop")]
public List<Loop> Loop { get; set; }
}
Here is the logic to DeSerialize the XML to Object
XmlSerializer serializer = new XmlSerializer(typeof(Type));
string xml = File.ReadAllText("XMLFile3.xml");
using (TextReader reader = new StringReader(xml))
{
var results = (Type)serializer.Deserialize(reader);
foreach (var item in results.Loop)
{
Console.WriteLine($"{item.LoopId} {item.Name}");
if (item.PER != null)
{
Console.WriteLine($"PER:{Regex.Replace(item.PER.PER01, #"\s+", "")}-{Regex.Replace(item.PER.PER02, #"\s+", "")}-{Regex.Replace(item.PER.PER03, #"\s+", "")}-{Regex.Replace(item.PER.PER04, #"\s+", "")}");
}
if (item.NM1 != null)
{
Console.WriteLine($"NM1:{Regex.Replace(item.NM1.NM101, #"\s+", "")}-{Regex.Replace(item.NM1.NM102, #"\s+", "")}");
}
if (item.LM != null)
{
Console.WriteLine($"LM:{Regex.Replace(item.LM.LM01, #"\s+", "")}-{Regex.Replace(item.LM.LM02, #"\s+", "")}");
}
}
}
OUTPUT
2100A MEMBER NAME
PER:IP--HP-6235834409
2100C MEMBER MAILING ADDRESS
NM1:31-1
2100G RESPONSIBLE PERSON
PER:IP--HP-6235834409
LM:RP-
I have an XML that I want to deserialize according to my own classes. It deserializes properly, but some of the values become null. It doesn't give an errors, and I'm not sure where the error lies.
I've tried changing the classes, serializing a memory model and then checking the output, but none of it worked to my liking. It needs to follow the XML that is provided.
My model:
[XmlRoot(ElementName = "model", Namespace = "http://www.archimatetool.com/archimate")]
public class Model
{
[XmlElement(ElementName = "folder")]
public List<Folder> Folders { get; set; }
[XmlElement(ElementName = "purpose")]
public string Purpose { get; set; }
[XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "archimate", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Archimate { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
My XML
<?xml version="1.0" encoding="UTF-8"?>
<archimate:model xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:archimate="http://www.archimatetool.com/archimate" name="Archisurance" id="11f5304f" version="3.1.1">
<folder name="Business" id="8c90fdfa" type="business">
<folder name="Actors" id="fa63373b">
<element xsi:type="archimate:BusinessInterface" id="1544" name="mail"/>
</folder>
</folder>
<purpose>An example of a fictional Insurance company.</purpose>
</archimate:model>
This the result im getting after deserializing.
I cant post pictures (due to reputation) so i am just posting a link.
result
I would expect the purpose field to say "An example of a fictional Insurance company", but it is null.
You can deserialize your XML with the following data model:
[XmlRoot(ElementName = "model", Namespace = "http://www.archimatetool.com/archimate")]
[XmlType(Namespace = "http://www.archimatetool.com/archimate")]
public class Model
{
[XmlElement(ElementName = "folder", Form = XmlSchemaForm.Unqualified)]
public List<Folder> Folders { get; set; }
[XmlElement(ElementName = "purpose", Form = XmlSchemaForm.Unqualified)]
public string Purpose { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "version")]
public string Version { get; set; }
}
[XmlType(Namespace = "http://www.archimatetool.com/archimate")]
public class Folder
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
[XmlAttribute(AttributeName = "type")]
public string Type { get; set; }
[XmlElement(ElementName = "folder", Form = XmlSchemaForm.Unqualified)]
public List<Folder> Folders { get; set; }
[XmlElement(ElementName = "element", Form = XmlSchemaForm.Unqualified)]
public List<Element> Element { get; set; }
}
[XmlType(Namespace = "http://www.archimatetool.com/archimate")]
[XmlInclude(typeof(BusinessInterface))]
public abstract class Element
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlType(TypeName = "BusinessInterface", Namespace = "http://www.archimatetool.com/archimate")]
public class BusinessInterface : Element
{
}
Notes:
The root element <archimate:model> is in the archimate: namespace, but its child elements are not in any namespace, since the archimate: namespace is not the default namespace. Thus it's necessary to indicate to XmlSerializer that these child elements are in a different namespace from their parent. Setting XmlElementAttribute.Form = XmlSchemaForm.Unqualified accomplishes this.
(It is not necessary to specify that attributes are in the default namespace, since all XML attributes are assumed to be unqualified unless otherwise specified.)
The presence of the xsi:type="archimate:BusinessInterface" attribute indicates the <element> attribute is part of a polymorphic type hierarchy. The xsi:type attribute is a standard w3c attribute that allows an element to explicitly assert its type. XmlSerializer supports this attribute and in fact requires the presence of a subtype corresponding to the xsi:type and declared through the [XmlInclude] attribute.
For details see How to: Control Serialization of Derived Classes.
Here I made an arbitrary choice of properties to include in the base class Element and the derived class BusinessInterface. You may need to adjust this choice given a more complete XML sample.
Sample fiddle here.
I want to Deserialize and get values of 2 attributes with different ID.
<Attributes><AddressAttribute ID="18"><AddressAttributeValue><Value>Sala 305</Value></AddressAttributeValue></AddressAttribute><AddressAttribute ID="17"><AddressAttributeValue><Value>3434</Value></AddressAttributeValue></AddressAttribute></Attributes>
I treid this C# code but it only returns the 1st attribute.
please help
[XmlRoot(ElementName = "AddressAttributeValue")]
public class AddressAttributeValue
{
[XmlElement(ElementName = "Value")]
public string Value { get; set; }
}
[XmlRoot(ElementName = "AddressAttribute")]
public class AddressAttribute
{
[XmlElement(ElementName = "AddressAttributeValue")]
public AddressAttributeValue AddressAttributeValue { get; set; }
[XmlAttribute(AttributeName = "ID")]
public string ID { get; set; }
}
[XmlRoot(ElementName = "Attributes")]
public class Attributes
{
[XmlElement(ElementName = "AddressAttribute")]
public AddressAttribute AddressAttribute { get; set; }
}
var xmlData= customer.BillingAddress.CustomAttributes;
XmlSerializer serializer = new XmlSerializer(typeof(Attributes));
Attributes data;
using (TextReader reader = new StringReader(xmlData))
{
data = (Attributes)serializer.Deserialize(reader);
}
Should I change classes of Deserialize logic???
Sometimes using Linq instead of xml serialization can be simpler
var list = XDocument.Parse(xmlstring).Descendants("AddressAttribute")
.Select(x => new
{
Id = (int)x.Attribute("ID"),
Value = (string)x.Element("AddressAttributeValue").Element("Value")
})
.ToList();
[XmlRoot(ElementName = "Attributes")]
public class Attributes
{
[XmlElement(ElementName = "AddressAttribute")]
public AddressAttribute AddressAttribute { get; set; }
}
Change it to:
[XmlRoot(ElementName = "Attributes")]
public class Attributes
{
[XmlElement(ElementName = "AddressAttribute")]
public AddressAttribute[] AddressAttribute { get; set; }
}
As you need to have collection of AddressAttribute you need to declare as an array.
I am having trouble deserializing XML. I get AccountInformation to work but it won't work with the Leauge elements. The XML doesn't contain any tag for "Leauges" and I don't want to add that tag to get it to work. Is there any other way to "fix" it? I have tried diffrent solutions but the deserialized result of the leauges comes back empty. What am I missing?
Any help appreciated!
Se my code below:
Update:
I have modified the code and the XML but I won't work anyway. What am I missing here?
[Serializable]
[XmlRoot(ElementName = "LeaugeCollection", Namespace = "")]
public class LeagueCollection
{
[XmlArray("Leagues")]
[XmlArrayItem("League",typeof(League))]
public League[] League { get; set; }
[XmlElement(ElementName = "AccountInformation")]
public string AccountInformation { get; set; }
}
[Serializable()]
public class League
{
[XmlElement(ElementName = "Id")]
public int Id { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "Country")]
public string Country { get; set; }
[XmlElement(ElementName = "Historical_Data")]
public string Historical_Data { get; set; }
[XmlElement(ElementName = "Fixtures")]
public string Fixtures { get; set; }
[XmlElement(ElementName = "LiveScore")]
public string Livescore { get; set; }
[XmlElement(ElementName = "NumberOfMatches")]
public int NumberOfMatches { get; set; }
[XmlElement(ElementName = "LatestMatch")]
public DateTime LatestMatch { get; set; }
}
Deserialize code:
public static void Main(string[] args)
{
XmlSerializer deserializer = new XmlSerializer(typeof(LeagueCollection));
TextReader reader = new StreamReader(#"C:\XmlFiles\XmlSoccer.xml");
object obj = deserializer.Deserialize(reader);
LeagueCollection XmlData = (LeagueCollection)obj;
reader.Close();
}
Link to XML:
Thanks in advance!
The XML you have in the image is missing the actual array element (Leauges), it has only the array items elements (Leauge), that is why you cannot get it deserialized!
UPDATE:
Ok, trying to reproduce your code, I now see that in your XML your elements are spelled "League" while in your code "Leauge"
FIX that first!
UPDATE2:
After the edits you have done according to my comments,it seems to work fine!
You are missing a namespace. I don't like both Leagues and League. Leagues is unnecessary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
LeagueCollection leagueCollection = new LeagueCollection() {
leagues = new Leagues() {
League = new List<League>() {
new League() {
Id = 1,
Name = "English Premier League",
Country = "England",
Historical_Data = "Yes",
Fixtures = "Yes",
Livescore = "Yes",
NumberOfMatches = 5700,
LatestMatch = DateTime.Parse( "2015-05-24T16:00:00+00:00")
},
new League() {
Id = 2,
Name = "English League Championship",
Country = "England",
Historical_Data = "Yes",
Fixtures = "Yes",
Livescore = "Yes",
NumberOfMatches = 5700,
LatestMatch = DateTime.Parse("2015-05-24T16:00:00+00:00")
}
}
},
AccountInformation = "Confidential info"
};
XmlSerializer serializer = new XmlSerializer(typeof(LeagueCollection));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, leagueCollection);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer deserializer = new XmlSerializer(typeof(LeagueCollection));
XmlTextReader reader = new XmlTextReader(FILENAME);
LeagueCollection XmlData = (LeagueCollection)deserializer.Deserialize(reader);
reader.Close();
}
}
[XmlRoot(ElementName = "LeaugeCollection")]
public class LeagueCollection
{
[XmlElement("Leagues")]
public Leagues leagues { get; set; }
[XmlElement(ElementName = "AccountInformation")]
public string AccountInformation { get; set; }
}
[XmlRoot("Leagues")]
public class Leagues
{
[XmlElement("League")]
public List<League> League { get; set; }
}
[XmlRoot("League")]
public class League
{
[XmlElement(ElementName = "Id")]
public int Id { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "Country")]
public string Country { get; set; }
[XmlElement(ElementName = "Historical_Data")]
public string Historical_Data { get; set; }
[XmlElement(ElementName = "Fixtures")]
public string Fixtures { get; set; }
[XmlElement(ElementName = "LiveScore")]
public string Livescore { get; set; }
[XmlElement(ElementName = "NumberOfMatches")]
public int NumberOfMatches { get; set; }
[XmlElement(ElementName = "LatestMatch")]
public DateTime LatestMatch { get; set; }
}
}
First, i tried on the internet different ways, but i didn't got what i want. i have viewmodel class with the following properties;
public class UserEntitySubmissionsReportViewModel
{
public UserEntitySubmissionsReportViewModel()
{
Submissions = new FinalUserEntitiesAssignmentViewModel();
}
public int Id { get; set; }
public int Status { get; set; }
public DateTime SubmissionDate { get; set; }
public int UserEntityAssignmentId { get; set; }
public FinalUserEntitiesAssignmentViewModel Submissions { get; set; }
}
and the nested class FinalUserEntitiesAssignmentViewModel whcih is;
[Serializable]
public class FinalUserEntitiesAssignmentViewModel
{
public FinalUserEntitiesAssignmentViewModel()
{
ProjectInformation = new ProjectInformationViewModel();
MilestoneInformation = new MilestoneInformationViewModel();
ActivityListInformation = new ActivityListInformationViewModel();
ActivityInformation = new ActivityInformationViewModel();
SubActivityInformation = new List<SubActivityInformationViewModel>();
}
[XmlElement(ElementName = "ProjectInformation")]
public ProjectInformationViewModel ProjectInformation { get; set; }
[XmlElement(ElementName = "MilestoneInformation")]
public MilestoneInformationViewModel MilestoneInformation { get; set; }
[XmlElement(ElementName = "ActivityListInformation")]
public ActivityListInformationViewModel ActivityListInformation { get; set; }
[XmlElement(ElementName = "ActivityInformation")]
public ActivityInformationViewModel ActivityInformation { get; set; }
[XmlElement(ElementName = "SubActivityInformation")]
public List<SubActivityInformationViewModel> SubActivityInformation { get; set; }
}
[Serializable]
public class ProjectInformationViewModel
{
[XmlElement(ElementName = "Id")]
public int Id { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
public string Description { get; set; }
}
When i serialize this, i only get the 1 property i.e Id for nested class.
var obj = new UserEntitySubmissionsReportViewModel();
var writer = new System.Xml.Serialization.XmlSerializer(typeof(UserEntitySubmissionsReportViewModel));
System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("~/App_Data/UserEntitySubmissionsReportViewModel.xml"));
writer.Serialize(file, obj);
file.Close();
The result i get is;
<?xml version="1.0" encoding="utf-8"?>
<UserEntitySubmissionsReportViewModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>0</Id>
<Status>0</Status>
<SubmissionDate>0001-01-01T00:00:00</SubmissionDate>
<UserEntityAssignmentId>0</UserEntityAssignmentId>
<Submissions>
<ProjectInformation>
<Id>0</Id>
</ProjectInformation>
<MilestoneInformation>
<Id>0</Id>
</MilestoneInformation>
<ActivityListInformation>
<Id>0</Id>
</ActivityListInformation>
<ActivityInformation>
<Id>0</Id>
<Attributes />
<Tools />
</ActivityInformation>
</Submissions>
</UserEntitySubmissionsReportViewModel>
As you can see, i am not able to serialize other properties. Similarly i have nest collection too. How can i serialize nested properties using C# ?
I think that when serializing XML that you need to define a default constructor for your classes. Try adding a construction for your ProjectInformationViewModel class.
public class ProjectInformationViewModel
{
// Default Constructor
public ProjectInformationViewModel()
{
}
}