Unusual XML Format I Must Iterate Through - c#

I need to iterate through some XML that has an unusual format to it. It looks like this:
<Baseball>
<Player playerID="123" playerName="John Smith" playerBats="Right"/>
<position positionID="1b" positionCode="abc" counter="3"/>
<position positionID="2b" positionCode="def" counter="2"/>
</Player>
</Baseball>
I cannot change this format that is given to me. I need to iterate through every line and different pieces get pulled and go to different places. I will be doing the code in C#. Ideas? Thank you!

Assuming your input XML actually IS valid XML, this is the pattern I use for this type of thing.
Your example XML isn't valid because Player is both self closing, and has an explicit closing tag. I've adjusted it to my best guess of what it should look like.
If that really is the XML you have to deal with, XmlDocument.LoadXml will throw an error. You will need to find some other way to deal with the malformed data, perhaps pre-processing the data to remove the / on the Player element so it is no longer self closing.
The basic pattern is that there is a class for each element in the XML. Each class has a static function FromXml that accepts an XmlElement for the matching element in the XML. FromXML is responsible for reading, parsing, and populating its properties from attributes. Child elements are processed by calling FromXml on their associated classes.
class Program
{
static void Main(string[] args)
{
string xml =
#"<Baseball>
<Player playerID=""123"" playerName=""John Smith"" playerBats=""Right"">
<position positionID=""1b"" positionCode=""abc"" counter=""3""/>
<position positionID=""2b"" positionCode=""def"" counter=""2""/>
</Player>
</Baseball>";
var document = new XmlDocument();
document.LoadXml(xml);
var players = new List<Player>();
foreach (XmlElement baseballElement in document.SelectNodes("Baseball"))
{
foreach (XmlElement playerElement in baseballElement.SelectNodes("Player"))
{
players.Add(Player.FromXml(playerElement));
}
}
Console.ReadLine();
}
}
public class Player
{
public static Player FromXml(XmlElement PlayerElement)
{
var player = new Player();
player.PlayerId = int.Parse(PlayerElement.GetAttribute("playerID"));
player.PlayerName = PlayerElement.GetAttribute("playerName");
player.PlayerBats = PlayerElement.GetAttribute("playerBats");
foreach (XmlElement positionElement in PlayerElement.SelectNodes("position"))
{
player.Positions.Add(Position.FromXml(positionElement));
}
return player;
}
public int PlayerId { get; set; }
public string PlayerName { get; set; }
public string PlayerBats { get; set; }
private List<Position> _positions = new List<Position>();
public List<Position> Positions
{
get { return _positions; }
}
}
public class Position
{
public static Position FromXml(XmlElement positionElement)
{
var position = new Position();
position.PositionId = positionElement.GetAttribute("positionID");
position.PositionCode = positionElement.GetAttribute("positionCode");
position.Counter = int.Parse(positionElement.GetAttribute("counter"));
return position;
}
public string PositionId { get; set; }
public string PositionCode { get; set; }
public int Counter { get; set; }
}
This will create a list of Player each of which contains a list of Position, all populated from the XML.
I also haven't done any kind of error checking on the input XML. If any attributes are missing or in the wrong format, it will throw an error.

Related

XML parsing nested objects with attributes for Unity dialogues system purpose

I'm trying to build a basic dialogue system to use in Unity starting from a XML document that look like this:
<?xml version="1.0" encoding="utf-8"?>
<speech id="1">
<bubble id="1" isQuestion="no">
Hi!
</bubble>
<bubble id="2" isQuestion="no">
It's been a while!
</bubble>
<bubble id="3" isQuestion="no">
Have a look at my wares!
</bubble>
<bubble id="4" isQuestion="yes">
Do you want to trade?
<option id="1"> true </option>
<option id="2"> false </option>
</bubble>
<bubble id="5" isQuestion="no">
Goodbye!
</bubble>
</speech>
<speech id="2">
...
</speech>
The concept here is to store each line in a "bubble" node with the id attributes to locate the node in the speech and a Boolean variable to know if the bubble ask a question.
To read that I've tried something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
public class DialogueManager
{
public List<Speech> LoadSpeechs(XmlDocument doc)
{
doc.Load();
List<Bouble> Boubles = new List<Bouble>();
List<Bouble> Speechs = new List<Speech>();
foreach (xmlNode node in doc.DocumentElement)
{
int id = node.Attributes[0].Value;
foreach (xmlNode node in doc.DocumentElement)
{
int id = node.Attributes[0].Value;
bool isQuestion = node.Attributes[1].Value;
string content = string.Parse(node["bouble"].InnerText);
bouble = new Bouble(id, isQuestion, value);
Boubles.Add(bouble);
}
speech = new Speech(id, Boubles);
Speechs.Add(speech);
}
return Speechs;
}
public class Speech
{
public int SpeechID { get; set; }
public Speech(int m_speechID, List<Bouble> bobules)
{
SpeechID = m_speechID;
Boubles = bobules;
}
}
public class Bouble
{
public bool IsQuesion { get; set; }
public int NodeID { get; set; }
public string Content { get; set; }
public Bouble(int m_nodeID, bool m_isQuestion, string m_value)
{
NodeID = m_nodeID;
IsQuesion = m_isQuestion;
Content = m_value;
}
}
}
The problem is that I get a tons of error, which are difficult to understand alone.
So here I am. I should mention that I'm not trying to realize something in particular just learning the paradigm and Unity so I prefer some comment and explanation on how this work and where I'm mistaken rather than other ways around, but all reply will be welcome :)
I'm planning on adding more attributes, but for now I'd like to figure how to make this work properly.
Based on my test, I find the following problem and you could make some changes.
First, we should have the root node when we want to read the xml files.
Here is my tested xml:
Second, we need to use type convert if we want to convert one type to another type.
Such as the following code:
int sid = Convert.ToInt32(node.Attributes[0].Value);
string content = Lnode.InnerText;(InnerText will return a string type, there is no need to convert again)
Third, we could use the following code convert "yes" or "no" to type bool.
text = Lnode.Attributes[1].Value.ToString();
if(text=="yes")
{
isquestion = true;
}
else
{
isquestion = false;
}
Fourth, we need to put the Speechs.Add(speech); to outside the inner loop.
Finally, you could refer to the following completed code example to convert xml to list.
Code:
public class DialogueManager
{
public List<Speech> LoadSpeechs(XmlDocument doc)
{
doc.Load("test.xml");
List<Bouble> Boubles = new List<Bouble>();
List<Speech> Speechs = new List<Speech>();
string text = string.Empty;
bool isquestion = false;
Speech speech = null;
foreach (XmlNode node in doc.DocumentElement)
{
if (node.Name == "speech")
{
int sid = Convert.ToInt32(node.Attributes[0].Value);
foreach (XmlNode Lnode in node.ChildNodes)
{
int bid = Convert.ToInt32(Lnode.Attributes[0].Value);
text = Lnode.Attributes[1].Value.ToString();
if(text=="yes")
{
isquestion = true;
}
else
{
isquestion = false;
}
string content = Lnode.InnerText;
Bouble bouble = new Bouble(bid, isquestion, content);
Boubles.Add(bouble);
}
speech = new Speech(sid, Boubles);
}
Speechs.Add(speech);
}
return Speechs;
}
public class Speech
{
public int SpeechID { get; set; }
public List<Bouble> Boubles { get; set; }
public Speech(int m_speechID, List<Bouble> bobules)
{
SpeechID = m_speechID;
Boubles = bobules;
}
}
public class Bouble
{
public bool IsQuesion { get; set; }
public int NodeID { get; set; }
public string Content { get; set; }
public Bouble(int m_nodeID, bool m_isQuestion, string m_value)
{
NodeID = m_nodeID;
IsQuesion = m_isQuestion;
Content = m_value;
}
}
}
Tested code and result:(I tested in console app)
static void Main(string[] args)
{
DialogueManager manager = new DialogueManager();
XmlDocument doc = new XmlDocument();
var list=manager.LoadSpeechs(doc);
foreach (DialogueManager.Speech speech in list)
{
Console.WriteLine(speech.SpeechID);
foreach (DialogueManager.Bouble bouble in speech.Boubles)
{
Console.WriteLine(bouble.NodeID);
Console.WriteLine(bouble.IsQuesion);
Console.WriteLine(bouble.Content);
}
}
Console.ReadKey();
}
First of all there is one issue with your XML file: You need a root element in a form like e.g.
<?xml version="1.0"?>
<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<speech>
...
</speech>
<speech>
...
</speech>
</Root>
Then instead of parsing this all "manually" you could/should use XMLSerializer.
This allows you to completely flexible add more elements and attributes without having to change the parser method all the time. You rather already define the entire XML scheme structure directly in the class definitions via attributes
and do something like e.g.
// In general make your classes Serializable and use fields instead of properties
// This way you can also see them in the Unity Inspector
// See https://docs.unity3d.com/Manual/script-Serialization.html
[Serializable]
// That generates/interprets the general XML root element
[XmlRoot]
public class Root
{
// By matching this element name with the root name of the Speech class (see below)
// This is treated as array without the need for an additional wrapper tag
[XmlElement(ElementName = "speech")] public List<Speech> speeches = new List<Speech>();
}
[Serializable]
// By using the same ElementName as root for this
// It will not read/write an additional array wrapper tag but rather direct children of the Root
[XmlRoot(ElementName = "speech")]
public class Speech
{
// Makes this an attribute without the speech tag
// NOTE: I think you wouldn't really need these
// They are elements in an array so you could rely on the index itself
[XmlAttribute] public int id;
[XmlElement("bubble")] public List<Bubble> bubbles = new List<Bubble>();
}
[Serializable]
[XmlRoot(ElementName = "bubble")]
public class Bubble
{
[XmlAttribute] public int id;
// This treats the label as the actual text between the tags
[XmlText] public string label;
// NOTE: Here I thought your bool is quite redundant, you don't need it
// simply check if there are options elements -> if so it is automatically a question
// if there are no options anyway -> there is no question
public bool isQuestion => options.Count != 0;
// If there are none in your XML file the list will simply stay empty
[XmlElement(ElementName = "option")] public List<Option> options = new List<Option>();
}
[Serializable]
[XmlRoot(ElementName = "option")]
public class Option
{
[XmlAttribute] public int id;
[XmlText] public string label;
// Optionally you could use some return value like a bool or enum
// but again, you can also simply go by index
}
This requires your XML file be slightly changed and look like e.g.
<?xml version="1.0"?>
<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<speech id="1">
<bubble id="1">Hallo</bubble>
<bubble id="2">World?
<option id="1">Yes</option>
<option id="2">Nope</option>
</bubble>
</speech>
<speech id="2">
<bubble id="1">Hi</bubble>
<bubble id="2">There!</bubble>
</speech>
</Root>
Then finally you can simply have two methods like e.g.
public class Example : MonoBehaviour
{
[Header("Input")]
[Tooltip("The FULL path to your file - for the example below I cheated ;) ")]
public string xmlFileUrl = Path.Combine(Application.streamingAssetsPath, "Example.xml");
[Header("Result")]
[Tooltip("The deserialized c# classes")]
public Root root;
// This allows you to call this method via the Inspector Context Menu
[ContextMenu(nameof(LoadFile))]
public void LoadFile()
{
// Open the file as a stream
using (var stream = File.Open(xmlFileUrl, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// create an XMLSerializer according to the root type
var serializer = new XmlSerializer(typeof(Root));
// Deserialize the file according to your implemented Root class structure
root = (Root) serializer.Deserialize(stream);
}
}
[ContextMenu(nameof(WriteFile))]
public void WriteFile()
{
// Delete the existing file
if (File.Exists(xmlFileUrl)) File.Delete(xmlFileUrl);
// create the StreamingAsset folder if not exists
// NOTE: Later in your app you want to use the StreamingAssets only
// if your file shall be read-only!
// otherwise use persistentDataPath
if(!Directory.Exists(Application.streamingAssetsPath)) Directory.CreateDirectory(Application.streamingAssetsPath);
// Create a new file as stream
using (var stream = File.Open(xmlFileUrl, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
{
var serializer = new XmlSerializer(typeof(Root));
// serialize the current Root class into the XML file
serializer.Serialize(stream, root);
}
#if UNITY_EDITOR
// in the editor refresh the AssetDataBase of Unity
// so you see the added files in the Project View
UnityEditor.AssetDatabase.Refresh();
#endif
}
}
And now you have access to the root and all its properties directly like e.g.
var isQuestion = root.speeches[0].bubbles[1].isQuestion;
and you can do the entire preparation and editing also directly via the Inspector in Unity.
Then as a final little personal touch I would rather use
[Serializable]
[XmlRoot]
public class Root
{
[XmlElement(ElementName = nameof(Speech))] public List<Speech> speeches = new List<Speech>();
}
[Serializable]
[XmlRoot(ElementName = nameof(Speech))]
public class Speech
{
...
[XmlElement(nameof(Bubble))] public List<Bubble> bubbles = new List<Bubble>();
}
[Serializable]
[XmlRoot(ElementName = nameof(Bubble))]
public class Bubble
{
...
[XmlElement(ElementName = nameof(Option))] public List<Option> options = new List<Option>();
}
[Serializable]
[XmlRoot(ElementName = nameof(Option))]
public class Option
{
...
}
and in the XML use the uppercase class names
<?xml version="1.0"?>
<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Speech id="1">
<Bubble id="1">Hallo</Bubble>
<Bubble id="2">World?
<Option id="1">Yes</Option>
<Option id="2">Nope</Option>
</Bubble>
</Speech>
<Speech id="2">
<Bubble id="1">Hi</Bubble>
<Bubble id="2">There!</Bubble>
</Speech>
</Root>

Serializing XML into object - "error in xml document (2,2)

Yes, I have read other threads on this subject but I am missing something:
I am trying to deserialize an XML document that, in part, contains logged SMS messages. The XML file takes the format of:
<reports>
<report>
<sms_messages>
<sms_message>
<number>4155554432</number>
<text>Hi! How are you?</text>
</sms_message>
<sms_message>
<number>4320988876</number>
<text>Hello!</text>
</sms_message>
</sms_messages>
</report>
</reports>
My code looks like:
[XmlType("sms_message")]
public class SMSMessage
{
[XmlElement("number")]
public string Number {get;set;}
[XmlElement("text")]
public string TheText {get;set;}
}
[XmlType("report")]
public class AReport
{
[XmlArray("sms_messages")]
public List<SMSMessage> SMSMessages = new List<SMSMessage>();
}
[XmlRoot(Namespace="www.mysite.com", ElementName="reports", DataType="string", IsNullable=true)]
public class AllReports
{
[XmlArray("reports")]
public List<AReport> AllReports = new List<AReport>();
}
I am trying to serialize it like this:
XmlSerializer deserializer = new XmlSerializer(typeof(AllReports));
TextReader tr = new StreamReader(this.tbXMLPath.text);
List<AllReports> reports;
reports = (List<AllReports>)deserializer.Deserialize(tr);
tr.close();
I get the error: "There is an error in XML document (2,2)" The inner exception states,<reports xmlns=''> was not expected.
I am sure it has something to do with the serializer looking for the namespace of the root node? Is my syntax correct above with the [XmlArray("reports")] ? I feel like something is amiss because "reports" is the root node and it contains a list of "report" items, but the decoration for the root node isn't right? This is my first foray into this area. Any help is greatly appreciated.
With a minimal change to your non-compilable code
XmlSerializer deserializer = new XmlSerializer(typeof(AllReports));
TextReader tr = new StreamReader(filename);
AllReports reports = (AllReports)deserializer.Deserialize(tr);
[XmlType("sms_message")]
public class SMSMessage
{
[XmlElement("number")]
public string Number { get; set; }
[XmlElement("text")]
public string TheText { get; set; }
}
[XmlType("report")]
public class AReport
{
[XmlArray("sms_messages")]
public List<SMSMessage> SMSMessages = new List<SMSMessage>();
}
[XmlRoot("reports")]
public class AllReports
{
[XmlElement("report")]
public List<AReport> Reports = new List<AReport>();
}

Building XML using Linq from a List<CustomClass>

I'm just trying to understand Linq and I am trying to do something that seems very simple, but I can't get it to output the way I would like. I have been stuck on this for days trying various different methods I just can't get it right.
So I have a class EarObs, it has members: eventID, icaoId, frm, sta, db.
I'm trying to build an XML document from a List. I want the XML document to look like so:
<EarObs EventId = "123456789">
<icao icaoID = "0001">
<frm frm = "01">
<sta sta = "00">
<db>87</db>
<hz>99</hz>
</sta>
<sta station = "01">
<db>79</db>
<hz>99</hz>
</sta>
</frm>
<frm frm = "02">
................
</frm>
</icao>
</EarObs>
And this would continue all the way down keeping the same order if there was more than one frame or more than one code etc.
So this is what I have been trying most recently but it still does not output they way I would like, Obs get repeated and I do not know where I am going wrong.
string eventGUID = "eventGUID";
List<EarObs> frameObsList = new List<EarObs>();
for (int frm = 2; frm > 0; frm--)
{
for (int sta = 5; sta > 0; sta--)
{
frameObsList.Add(new EarObs("KAPF", eventGUID, frm, sta, 85 + sta, 99 + sta));
cnt++;
}
}
String eventID = obsList.First().EventGUID;
List<EarObs> distinctApts =
obsList
.GroupBy(p => p.IcaoId)
.Select(g => g.First())
.ToList();
XElement xElement = new XElement("EarObs", new XAttribute("eventID", eventID),
from ea in distinctApts
orderby ea.IcaoId
select new XElement("icao", new XAttribute("code", ea.IcaoId),
from eb in obsList
where ea.IcaoId == eb.IcaoId
orderby eb.Frm
select new XElement("frm", new XAttribute("frm", eb.Frm),
from ec in obsList
where eb.Frm == ec.Frm
orderby ec.Sta
select new XElement("sta", new XAttribute("sta", ec.Sta),
new XElement("db", ec.Db),
new XElement("hz", ec.Hz)))));
Using this code I get an xml document that repeats the frame once for each station. This is not correct. I feel like this is easily done sequentially, but I'm trying to learn and this seems just so simple that I should be able to do it in Linq. I need each element in the List to only be represented in the XML document once. How do I go about this?
I would also like to expand it so that it can handle multiple eventId's as well, but that is not as important as getting the XML structure right. Any help would be much appreciated, I haven't been able to find too many example of creating an XML including the filtering of the elements using linq, most examples seem to have the List all ready structured before they create the XML.
Since you have a custom class, EarObs why not define Xml attributes to your object and serialize the object using the XmlSerlizer class? This way, you can continue use Linq on your objects, and also output your objects.
e.g. Below is a team, with players on it.
[XmlRoot("root")]
public class Team
{
private List<Player> players = new List<Player>();
[XmlElement("player")]
public List<Player> Players { get { return this.players; } set { this.players = value; } }
// serializer requires a parameterless constructor class
public Team() { }
}
public class Player
{
private List<int> verticalLeaps = new List<int>();
[XmlElement]
public string FirstName { get; set; }
[XmlElement]
public string LastName { get; set; }
[XmlElement]
public List<int> vertLeap { get { return this.verticalLeaps; } set { this.verticalLeaps = value; } }
// serializer requires a parameterless constructor class
public Player() { }
}
Once I create a team, with some players on it, I just have to do:
Team myTeamData = new Team();
// add some players on it.
XmlSerializer deserializer = new XmlSerializer(typeof(Team));
using (TextReader textReader = new StreamReader(#"C:\temp\temp.txt"))
{
myTeamData = (Team)deserializer.Deserialize(textReader);
textReader.Close();
}
The output will look like this:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<player>
<FirstName>dwight</FirstName>
<LastName>howard</LastName>
<vertLeap>1</vertLeap>
<vertLeap>2</vertLeap>
<vertLeap>3</vertLeap>
</player>
<player>
<FirstName>dwight</FirstName>
<LastName>howard</LastName>
<vertLeap>1</vertLeap>
</player>
</root>
The easiest way is to create a set of classes to handle the serialization like so;
public class sta
{
public int db { get; set; }
public int hz { get; set; }
[XmlAttribute()]
public string station { get; set; }
}
public class frm
{
[XmlAttribute("frm")]
public string frmID { get; set; }
[XmlElement("sta")]
public List<sta> stas { get; set; }
}
public class icao
{
[XmlAttribute]
public string icaoID { get; set; }
[XmlElement("frm")]
public List<frm> frms { get; set; }
}
public class EarObs
{
[XmlAttribute]
public string EventId { get; set; }
[XmlElement("icao")]
public List<icao> icaos { get; set; }
}
and you can use the xml serializer to serialize/deserialize. The following serializes to the structure identical to what you have;
XmlSerializer serializer = new XmlSerializer(typeof(EarObs));
EarObs obs = new EarObs() { EventId = "123456789" };
obs.icaos = new List<icao>();
obs.icaos.Add(new icao() { icaoID = "0001" });
obs.icaos[0].frms = new List<frm>();
obs.icaos[0].frms.Add(new frm() { frmID = "01" });
obs.icaos[0].frms[0].stas = new List<sta>();
obs.icaos[0].frms[0].stas.Add(new sta() { station = "00", db = 87, hz = 99 });
obs.icaos[0].frms[0].stas.Add(new sta() { station = "01", db = 79, hz = 99 });
obs.icaos[0].frms.Add(new frm() { frmID = "02" });
using (StringWriter s = new StringWriter())
{
serializer.Serialize(s, obs);
string test = s.ToString();
}
Outputs;
<?xml version="1.0" encoding="utf-16"?>
<EarObs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" EventId="123456789">
<icao icaoID="0001">
<frm frm="01">
<sta station="00">
<db>87</db>
<hz>99</hz>
</sta>
<sta station="01">
<db>79</db>
<hz>99</hz>
</sta>
</frm>
<frm frm="02" />
</icao>
</EarObs>
Now, while this seems like a lot of trouble to go to, it's possible to use the xsd.exe tool (comes with the framework I believe), to automatically create a set of classes that match any given xml file, although it does use an intermediary xsd file (painless though). You can find out how here; How to generate .NET 4.0 classes from xsd?

C# Serialize a class with a List data member

I have this c# class:
public class Test
{
public Test() { }
public IList<int> list = new List<int>();
}
Then I have this code:
Test t = new Test();
t.list.Add(1);
t.list.Add(2);
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
StringWriter sw = new StringWriter();
XmlSerializer xml = new XmlSerializer(t.GetType());
xml.Serialize(sw, t);
When I look at the output from sw, its this:
<?xml version="1.0" encoding="utf-16"?>
<Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
the values 1,2 I added to the list member variable dont show up.
So how can I fix this ? I made the list a property but it still doesnt seem to work.
I am using xml serialization here, are there any other serializers ?
I want performance! Is this the best approach ?
--------------- UPDATE BELOW -------------------------
So the actual class I want to serialize is this:
public class RoutingResult
{
public float lengthInMeters { get; set; }
public float durationInSeconds { get; set; }
public string Name { get; set; }
public double travelTime
{
get
{
TimeSpan timeSpan = TimeSpan.FromSeconds(durationInSeconds);
return timeSpan.TotalMinutes;
}
}
public float totalWalkingDistance
{
get
{
float totalWalkingLengthInMeters = 0;
foreach (RoutingLeg leg in Legs)
{
if (leg.type == RoutingLeg.TransportType.Walk)
{
totalWalkingLengthInMeters += leg.lengthInMeters;
}
}
return (float)(totalWalkingLengthInMeters / 1000);
}
}
public IList<RoutingLeg> Legs { get; set; } // this is a property! isnit it?
public IList<int> test{get;set;} // test ...
public RoutingResult()
{
Legs = new List<RoutingLeg>();
test = new List<int>(); //test
test.Add(1);
test.Add(2);
Name = new Random().Next().ToString(); // for test
}
}
But the XML produced by the serializer is this:
<RoutingResult>
<lengthInMeters>9800.118</lengthInMeters>
<durationInSeconds>1440</durationInSeconds>
<Name>630104750</Name>
</RoutingResult>
???
its ignoring both of those lists ?
1) Your list is a field, not a property, and the XmlSerializer will only work with properties, try this:
public class Test
{
public Test() { IntList = new List<int>() }
public IList<int> IntList { get; set; }
}
2) There are other Serialiation options, Binary the main other one, though there is one for JSON as well.
3) Binary is probably the most performant way, since it is typically a straight memory dump, and the output file will be the smallest.
list is not a Property. Change it to a publicly visible property, and it should be picked up.
I figured it out that XmlSerializer doesnt work if I use IList so I changed it to List, that made it work. As Nate also mentioned.

XML Serialization - XmlCDataSection as Serialization.XmlText

I am having problems serializing a cdata section using c#
I need to serialize XmlCDataSection object property as the innertext of the element.
The result I am looking for is this:
<Test value2="Another Test">
<![CDATA[<p>hello world</p>]]>
</Test>
To produce this, I am using this object:
public class Test
{
[System.Xml.Serialization.XmlText()]
public XmlCDataSection value { get; set; }
[System.Xml.Serialization.XmlAttributeAttribute()]
public string value2 { get; set; }
}
When using the xmltext annotation on the value property the following error is thrown.
System.InvalidOperationException:
There was an error reflecting property
'value'. --->
System.InvalidOperationException:
Cannot serialize member 'value' of
type System.Xml.XmlCDataSection.
XmlAttribute/XmlText cannot be used to
encode complex types
If I comment out the annotation, the serialization will work but the cdata section is placed into a value element which is no good for what I am trying to do:
<Test value2="Another Test">
<value><![CDATA[<p>hello world</p>]]></value>
</Test>
Can anybody point me in the right direction to getting this to work.
Thanks, Adam
Thanks Richard, only now had chance to get back to this. I think I have resolved the problem by using your suggestion. I have created a CDataField object using the following:
public class CDataField : IXmlSerializable
{
private string elementName;
private string elementValue;
public CDataField(string elementName, string elementValue)
{
this.elementName = elementName;
this.elementValue = elementValue;
}
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter w)
{
w.WriteStartElement(this.elementName);
w.WriteCData(this.elementValue);
w.WriteEndElement();
}
public void ReadXml(XmlReader r)
{
throw new NotImplementedException("This method has not been implemented");
}
}
The way Test is defined, your data is a CData object. So the serialisation system is trying to preserve the CData object.
But you want to serialise some text data as a CData section.
So first, the type of Test.value should be String.
You then need to control how that field is serialised, but there does not appear to be any inbuilt method or attribute to control how strings are serialised (as string, maybe with entities for reserved characters, or as CDATA). (Since, from an XML infoset perspective all of these are the same, this is not surprising.)
You can of course implemented IXmlSerializable and just code the serialisation of the Test type yourself which gives you complete control.
This basically shorter version of Jack answer with better error messages:
[XmlIgnore]
public string Content { get; set; }
[XmlText]
public XmlNode[] ContentAsCData
{
get => new[] { new XmlDocument().CreateCDataSection(Content) };
set => Content = value?.Cast<XmlCDataSection>()?.Single()?.Data;
}
Just found an alternative from here:
[XmlIgnore]
public string Content { get; set; }
[XmlText]
public XmlNode[] CDataContent
{
get
{
var dummy = new XmlDocument();
return new XmlNode[] {dummy.CreateCDataSection(Content)};
}
set
{
if (value == null)
{
Content = null;
return;
}
if (value.Length != 1)
{
throw new InvalidOperationException(
String.Format(
"Invalid array length {0}", value.Length));
}
var node0 = value[0];
var cdata = node0 as XmlCDataSection;
if (cdata == null)
{
throw new InvalidOperationException(
String.Format(
"Invalid node type {0}", node0.NodeType));
}
Content = cdata.Data;
}
}
}
I had very same problem as Adam. However this Answer does not helped me at 100% :) but gives me a clue. So I'va created a code like below. It generates XML like this:
<Actions>
<Action Type="reset">
<![CDATA[
<dbname>longcall</dbname>
<ontimeout>
<url>http://[IPPS_ADDRESS]/</url>
<timeout>10</timeout>
</ontimeout>
]]>
</Action>
<Action Type="load">
<![CDATA[
<dbname>longcall</dbname>
]]>
</Action>
</Actions>
Code:
public class ActionsCDataField : IXmlSerializable
{
public List<Action> Actions { get; set; }
public ActionsCDataField()
{
Actions = new List<Action>();
}
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter w)
{
foreach (var item in Actions)
{
w.WriteStartElement("Action");
w.WriteAttributeString("Type", item.Type);
w.WriteCData(item.InnerText);
w.WriteEndElement();
w.WriteString("\r\n");
}
}
public void ReadXml(XmlReader r)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(r);
XmlNodeList nodes = xDoc.GetElementsByTagName("Action");
if (nodes != null && nodes.Count > 0)
{
foreach (XmlElement node in nodes)
{
Action a = new Action();
a.Type = node.GetAttribute("Type");
a.InnerText = node.InnerXml;
if (a.InnerText != null && a.InnerText.StartsWith("<![CDATA[") && a.InnerText.EndsWith("]]>"))
a.InnerText = a.InnerText.Substring("<![CDATA[".Length, a.InnerText.Length - "<![CDATA[]]>".Length);
Actions.Add(a);
}
}
}
}
public class Action
{
public String Type { get; set; }
public String InnerText { get; set; }
}

Categories

Resources