LINQ XML Get value of element from multiple where statement - c#

First question on SO, apologies if I mess some of this up. I'm new to c# and LINQ and have spent the past 2 days searching SO for a solution, none seem to be exactly what I'm after. So...
The xml file I'm querying is generated from a DICOM Structured Report file. I'm trying to get specific values of elements from this xml file. These elements correspond to specific measurements that were taken during an ultrasound examination. The entire xml file is 15k lines long so for simplicity I've edited it. I'll just show one example of what I'm trying to do but the process will be the same for all other elements I'm looking to get.
The element I want to get has to meet 3 criteria, in this case Tricuspid Valve, Peak Velocity and Regurgitant Flow but this changes depending on the measurement that was taken. Once those criteria are met I want to get the value of , which in this case is 2120.
The xml
<report type="Comprehensive SR">
<document>
<content>
<container flag="SEPARATE">
<container flag="SEPARATE">
<code>
<meaning>Tricuspid Valve</meaning>
</code>
<container flag="SEPARATE">
<num>
<concept>
<meaning>Peak Velocity</meaning>
</concept>
<code>
<meaning>Regurgitant Flow</meaning>
</code>
<value>2120</value>
<unit>
<value>mm/s</value>
</unit>
</num>
My code in c#
XDocument xmlSR = XDocument.Load("DICOMSRtest.xml");
var TRVmax = from c in xmlSR.Descendants("container")
where (string)c.Element("code").Element("meaning") == "Tricuspid Valve"
where (string)c.Element("concept").Element("meaning") == "Peak Velocity"
where (string)c.Element("code").Element("meaning") == "Regurgitant Flow"
select c.Element("container").Element("num").Element("value");
Console.Write("TRVmax: " + TRVmax);
When I run the code I get the following
TRVmax: System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.Xml.Linq.XElement]
Any help or direction to some documentation which I can read to solve this would be greatly appreciated.

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XDocument doc = XDocument.Load("PurchaseOrder.xml");
List<XElement> xContainers = doc.Descendants("container").Where(x => x.Element("num") != null).ToList();
List<Container> containers = new List<Container>();
foreach (XElement xContainer in xContainers)
{
Container newContainer = new Container();
containers.Add(newContainer);
newContainer.code = (string)xContainer.Descendants("code").FirstOrDefault();
newContainer.concept = (string)xContainer.Descendants("concept").FirstOrDefault();
newContainer.value = (int)xContainer.Descendants("value").FirstOrDefault();
newContainer.unit = (string)xContainer.Descendants("unit").FirstOrDefault();
}
}
}
public class Container
{
public string code { get; set; }
public string concept { get; set; }
public int value { get; set; }
public string unit { get; set; }
}
}

Related

Can I use WebUtility.HtmlDecode to decode XML?

I have an XML-encoded attribute value. This is actually from a processing instruction. So the original data looks something like this:
<root><?pi key="value" data="<foo attr="bar">Hello world</foo>" ?></root>
I can parse it like this:
using System;
using System.Linq;
using System.Xml.Linq;
public class Program
{
private const string RawData = #"<root><?pi key=""value"" data=""<foo attr="bar">Hello world</foo>"" ?></root>";
public static void Main()
{
XDocument doc = GetXDocumentFromProcessingInstruction();
IEnumerable<XElement> fooElements = doc.Descendants("foo");
// ...
}
private static XProcessingInstruction LoadProcessingInstruction()
{
XDocument doc = XDocument.Parse(rawData);
return doc
.DescendantNodes()
.OfType<XProcessingInstruction>()
.First();
}
private static XDocument GetXDocumentFromProcessingInstruction()
{
XProcessingInstruction processingInstruction = LoadProcessingInstruction();
// QUESTION:
// Can there ever be a situation where HtmlDecode wouldn't decode the XML correctly?
string decodedXml = WebUtility.HtmlDecode(processingInstruction.Data);
// This works well, but it contains the attributes of the processing
// instruction as text.
string dummyXml = $"<dummy>{xml}</dummy>";
return XDocument.Parse(dummyXml);
}
This works absolutely fine, as far as I can tell.
But I am wondering if there might be some edge cases where it may fail, because of differences in how data would be encoded in XML vs. HTML.
Anybody have some more insight?
Edit:
Sorry, I made some incorrect assumptions about XProcessingInstruction.Data, but the code above was still working fine, so my question stands.
I have nonetheless rewritten my code and wrapped everything in an XElement, which (of course) removed the issue altogether:
private static XDocument GetXDocumentFromProcessingInstruction2()
{
XProcessingInstruction processingInstruction = LoadProcessingInstruction();
string encodedXml = string.Format("<dummy {0} />", processingInstruction.Data);
XElement element = XElement.Parse(encodedXml);
string parsedXml = element.Attribute("data").Value;
return XDocument.Parse(parsedXml);
}
So this does exactly what I need. But since WebUtility.HtmlDecode worked sufficiently well, I would still like to know if there could have been a situation where the first approach could have failed.
Removing the question marks and adding a forward slash at end of your input I got this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "<pi data=\"<foo attr="bar">Hello world</foo>\" />";
XElement pi = XElement.Parse(input);
string data = (string)pi.Attribute("data");
XElement foo = XElement.Parse(data);
string attr = (string)foo.Attribute("attr");
string innertext = (string)foo;
}
}
}

Remove Nodes Depending on Dynamic ID, C#, XML

I have this XML File
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Mobiles>
<Mobile ID="98a2d0b9c2661725a7486423ebd94abdef53ed89051ff5ac7a9c63a4b2a99d7a" RegDate="26/05/2017">
<FullName>Galaxy S-4</FullName>
<Vendor>Samsung</Vendor>
<Date>2010</Date>
<Price>30000SYP</Price>
<Weight>5g</Weight>
<Features>All</Features>
<Notifecations></Notifecations>
<Picture>/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCADCAQQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi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/wCS5NfYlFae2YuVHxqmg61D9zSdQXdwy/ZZAGGQ2CNvIyqnB7gelKdMv0+/o8//AIDyj+VfZFGKTq36Bynx4lrqX/QMnX/t3f8ArmrcGlak/wA/9n3zf9u7n+lfW2xf7q06j2r7BynytaaVqTyfurG5V/8AahZD/wCPAVoReG9fvJ9q6PqEjfd3fZ2I/wC+jwPzr6aoo9qxciPF/Dfwpv7idLjXkS0tV5a3Vg0r+xIyqj3BJ+nWvYoYo4YUiiVViRQqqvQAdAKmpKhyb3KSSFrzr4lfDC18cwJeW8q2eswLsjmZfklXqFfHOM9GHIyeD0r0WikM+PtU+G3jjQpmWXQbydS3+sso/PVvf5MkD6gVlnTNdi/4+NP1KD/f09/8K+1aK09oyeVHxOIbr+N51/7cWp6QzvIqLdy7mbaq/YXJY+gAHJr7VpMU/a+QcqPi0W100mxLiRnZtqr9hkzn0A29aPJuPu/a5d33dv2GT/CvtKil7RhynxcIL1/9VLct/u6e9S/2N4im/wBVp+sy/wDXPTXGfxxX2bRR7Rhyo+RNH+FHjPWpF8rRZ7RGPzTaj+5C+5B+b8lNfQnw8+Hdh4E06QJJ9p1K5A+03TLjgdEUdlH5k8nsB21LUuTY0rBRRRUjCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//2Q==</Picture>
</Mobile>
<Mobile ID='00283f5aa9c0c68c342c02977051757a7faae0ee70b086e628da7cc5baef2100' RegDate="26/05/2017">
<FullName>6600</FullName>
<Vendor>Nokia</Vendor>
<Date>2006</Date>
<Price>200SYP</Price>
<Weight>10g</Weight>
<Features>blutooth</Features>
<Notifecations></Notifecations>
<Picture>/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjI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B46ZwOM1D4c0G/0nRrvTJZ7ZpLgeWJGcAqFXb9xC2WxjJyOg9KAJvEFtLf+F9SEIjtrY2zNH5i/NJjDLx/CMgdeT6d62PhDfrd+EZoVMm22u3jjWU/MEIDD+Z/KsuUfboSqBtQcoMvMV8pCR02/dUjtklvTNN+DMjNHrELdN8cg/X/AAFDGtz1eiiipLCiiigDwD4iWP8AY3iW5hK/6Nct9rhGOzffH5lvzFcvoGuWuga/p8UiyR/Z5CjyRSMrSRv1yQc4HysOexr2b4s+Hf7X8JSXtuha80wNOm0ZZkx86j8ADj/ZFfO+pD7ZpsN9GoLwYSTjqvb+opkM+gXbNvJbtNqKsAGyiTEGUEHn5TgZA7k1EjLOwaKxup4ZMMBL5mCCMnIfC5zWH4F12LXdGtFbUFXUYRtkjlUZIUYVvvLuyAB3II5rZuLYQtMbu4XABBZI1QBQdyjLMw/j447UIRVJZ4bZLxyyoqoLWJiSMEDAIGA3HRQTxwRUXwbONS1ePttU/r/9eql5rdtp8Ej2BZ5A5IumYnGTnAfoRyRtQYOOcVo/CCxljn1W7ZCiMETkdCecfXGD/wACFNlI9ZoooqSgooooAayhhggEHqD3r5v8b+CbzwZrdzdWlk914fvCchRuEQPJVvTHY9MY719I0YHpQJo+U9K0S3uQJrSe8aBvuoNPkmz+KjFdvpXhvUxtNroepTt03C0itQP+BSkH8ga92ooFynmtn4B1K6nWbUJbWyUf3P8ASZ/wZgFX8FNd5pum22lWK2topWMckscsxPUk9yfWrtFBQtFFFAH/2Q==</Picture>
</Mobile>
</Mobiles>
When I try to remove Mobile element depending on IDtextbox.text rather than static value in XPath expression it doesn't execute
I'm using Windows application in Visual Studio 2010, C# language
I need two examples:
1- Depending on an element inside the parent element.
2- depending on an attribute of the parent element, make sure that attribute is not an integer value, it's code.
Notice: I have searched for many websites and view multiple solutions nobody mention about using control value in XPath expressions.
Use xml linq which is better in this case than xpath
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> mobiles = doc.Descendants("Mobile").ToList();
mobiles = mobiles.Where(x => (string)x.Element("FullName") != "Galaxy S-4").ToList();
mobiles = mobiles.Where(x => (string)x.Attribute("RegDate") != "26/05/2017").ToList();
doc.Descendants("Mobiles").FirstOrDefault().ReplaceWith(new XElement("Mobiles", mobiles));
}
}
}
thanks, Mr.jdweng
I solve the problem with this code
XDocument doc = XDocument.Load(#"Mobiles.xml");
List<XElement> mobiles = doc.Descendants("Mobile").ToList();
//mobiles = mobiles.Where(x => (string)x.Element("ID") == ID).ToList();
mobiles = mobiles.Where(x => (string)x.Attribute("ID") == ID).ToList();
doc.Descendants("Mobile").FirstOrDefault().ReplaceWith();
Best regards

C# Functions to accept arguments from XML

This is an extension of a question I had beforehand
I have a specific function that I want to run, and it is located inside an XML File:
Console.WriteLine("Text for test, {0}, {1}", testWord, testWord2);
The text is stored in an XML file:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<world>
<region name="TestRegion">
<area name="TestArea">
<building name="Outside">
<room name="TutorialRoom">
<textToDisplay>"Text for test, {0},{1}"</textToDisplay>
<extraString>testWord,tesWord2</extraString>
</room>
</building>
</area>
</region>
</world>
</root>
I can easily get the string data using LINQ
XElement xelement = XElement.Load("..\\..\\LocationDatabase.xml");
var textToDisplay= xelement.Elements("world")
.Elements("region").Where(region => (string)region.Attribute("name") == "TestRegion")
.Elements("area").Where(area => (string)area.Attribute("name") == "TestArea")
.Elements("building").Where(building => (string)building.Attribute("name") == "Outside")
.Elements("room").Where(room => (string)room.Attribute("name") == "TutorialRoom")
.Elements("textToDisplay");
var extraString= xelement.Elements("world")
.Elements("region").Where(region => (string)region.Attribute("name") == "TestRegion")
.Elements("area").Where(area => (string)area.Attribute("name") == "TestArea")
.Elements("building").Where(building => (string)building.Attribute("name") == "Outside")
.Elements("room").Where(room => (string)room.Attribute("name") == "TutorialRoom")
.Elements("extraString");
And this works completely fine. The issue I have is when I don't have a word in the XML file, but rather a property of a class. I have a singleton Player, and it has a autoproperty Name. To normally access it, I can just say:
Console.WriteLine("Your name is:", Player.Instance.Name);
But how do I, instead, keep this in the XML file? Like:
<?xml version="1.0" encoding="utf-8" ?>
<root>
<world>
<region name="TestRegion">
<area name="TestArea">
<building name="Outside">
<room name="TutorialRoom">
<textToDisplay>"Your name is: {0}"</textToDisplay>
<extraString>Player.Instance.Name</extraString>
</room>
</building>
</area>
</region>
</world>
</root>
When I use the past command, it simple thinks that whole section is a string, and outputs "Your name is: Player.Instance.Name"
An example using my own code:
The Player Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuardsOfAetheria
{
class Player
{
public enum Class
{
Melee,
Magic,
Ranged
}
public string Name { get; set; }
public Class PlayerClass { get; set; }
private static readonly Player instance = new Player();
static Player()
{
}
private Player()
{
}
public static Player Instance
{
get
{
return instance;
}
}
}
}
Is there a way to solve this?
EDIT 1:
I was able to do something similar using the following lines of code:
var typ = typeof(Player);
var prop = typ.GetProperty("Name");
var propVal = prop.GetValue(Player.Instance);
Console.WriteLine(((string)textToDisplay.First()).Replace(#"\n", Environment.NewLine), propVal);
This works fine, and gets the necessary data. The issue here is that in different parts, different classes have to be called var typ = typeof(Player), and different instances have to be attributed var propVal = prop.GetValue(Player.Instance). I can store the name of the class and instance I need to get from, but simply using a string that holds that data doesn't work, like below:
string className = "Player";
var typ = typeof(className);
var prop = typ.GetProperty("Name");
var propVal = prop.GetValue(Player.Instance);
Console.WriteLine(((string)textToDisplay.First()).Replace(#"\n", Environment.NewLine), propVal);
Is there anyway to do that?
Type player = Type.GetType("Player");
or
Type player = Type.GetType("myNamespace.Player");
See here for more info
Then you are going to have to get an instance of that type, see manipulating types. Then you will need to get the PropertyInfo's for the type, then get the one you want Instance, etc for Instance object.
You will need to get into intimate detail of telling the compiler what object your working with and what properties you want to access. Reflection is a runtime compiled way of accessing objects. It is definitely more complicated than the run-of-the-mill program.

C# Rotate Images From Url's Stored in XML File

Im trying to monetize a free winform app, basically I want to have 10 images rotate every 5 min in a picture box. I dont want to hard code these into the app, but store the image url's on my server in a xml file.
this is the xml on my server
<?xml version="1.0" encoding="utf-8"?>
<Advertisements>
<Ad>
<ImageUrl1>http://example.com/example.jpg</ImageUrl1>
<url1>http://example.com</url1>
</Ad>
<Ad>
<ImageUrl2>http://example.com/example2.jpg</ImageUrl2>
<url2>http://example.com</url2>
</Ad>
</Advertisements>
Im stuck on how to rotate through each node and display the image for 5 min
Tried to find a decent example, but most are for ASP.net
This is the code in my app:
XmlTextReader reader = null;
try {
string xmlURL = "http://example.com/ads.xml";
reader = new XmlTextReader(xmlURL);
reader.MoveToContent();
string elementName = "";
if ((reader.NodeType == XmlNodeType.Element) &&
(reader.Name == "Advertisements")) {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element)
elementName = reader.Name;
else {
if ((reader.NodeType == XmlNodeType.Text) &&
(reader.HasValue)) {
switch (elementName)
{
case "ImageUrl1":
picturebox.ImageLocation=reader.Value);
break;
}
}
}
}
}
}
catch (Exception) {
}
finally {
if (reader != null) reader.Close();
}
Your current code uses the older XmlReader approach to parsing XML manually. This is usually complex and tricky to get right. If you are using .NET version 3.5 or higher, you can use LINQ to XML for a cleaner interface to working with XML.
The approach I would take to solving your problem is this:
On app start-up, load the list of Advertisements from the server and cache the result in a static variable
Shuffle the list once (after loading it), so you can just keep iterating over the list when picking a new Ad to show (no need to randomize)
Use a Timer instance to rotate the image every 5 minutes
Here is some sample C# code using LINQ to XML for loading your XML data:
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace StackOverflowQ21588436
{
public class Example
{
private const string XML =
#"<?xml version=""1.0"" encoding=""utf-8""?>
<Advertisements>
<Ad>
<ImageUrl>http://example.com/example.jpg</ImageUrl>
<url>http://example.com</url>
</Ad>
<Ad>
<ImageUrl>http://example.com/example2.jpg</ImageUrl>
<url>http://example.com/2.html</url>
</Ad>
</Advertisements>";
public static IList<Advertisement> GetAdvertisements()
{
var xmlDocument = XDocument.Parse(XML); // or XDocument.Load(url)
var adXmlNodes = xmlDocument.Element("Advertisements").Elements("Ad");
var adList = adXmlNodes.Select(xmlNode => new Advertisement {
ImageUrl = xmlNode.Element("ImageUrl").Value,
Href = xmlNode.Element("url").Value
}).ToList();
return adList;
}
}
public class Advertisement
{
public string ImageUrl { get; set; }
public string Href { get; set; } // named 'Href' to show property names don't have to match XML
}
}

XmlRoot() for Xml Serilization does not work

I'm trying to get my httphandler to print out an XML file with the format:
<ScheduledShows>
<ScheduledShowElement>...</ScheduledShowElement>
<ScheduledShowElement>...</ScheduledShowElement>
<ScheduledShowElement>...</ScheduledShowElement>
</ScheduledShows>
But for some reason, the attribute XmlRoot("ScheduledShowElement") in ScheduledShow.cs is not working the way i want it to work. Instead, the output i get is:
<ScheduledShows>
<ScheduledShow>...<ScheduledShow>
<ScheduledShow>...<ScheduledShow>
<ScheduledShow>...<ScheduledShow
</ScheduledShows>
Basically, the name of the node is not being overriden to . How do i get my xml serializer to label nodes as ?
Below is my code and xml output. Thanks!
OneDayScheduleHandler.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml.Serialization;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.IO;
using System.Xml;
using System.Text;
using CommunityServer.Scheduler;
namespace CommunityServer.Scheduler
{
public class OneDayScheduleHandler : IHttpHandler
{
private readonly int NoLimitOnSize = -1;
public void ProcessRequest(HttpContext context)
{
int offsetInDays, timezone, size;
DateTime selectedDateTime;
Int32.TryParse(context.Request.QueryString["timezone"], out timezone);
Int32.TryParse(context.Request.QueryString["daysToOffset"], out offsetInDays);
if (!String.IsNullOrEmpty(context.Request.QueryString["size"]))
{
Int32.TryParse(context.Request.QueryString["size"], out size);
}
else
{
size = NoLimitOnSize;
}
if (timezone < (int)ScheduleConstants.TimeZone.Eastern)
{
selectedDateTime = DateTime.Now.AddMinutes(-180);
}
else
{
selectedDateTime = DateTime.Now;
}
selectedDateTime = selectedDateTime.AddDays(offsetInDays);
context.Response.ContentType = "text/xml";
context.Response.Write(SerializeToXML((List<ScheduledShow>)GetSheduledShowsByDateTime(selectedDateTime, size)));
}
public bool IsReusable
{
get
{
return false;
}
}
public static IList<ScheduledShow> GetSheduledShowsByDateTime(DateTime date, int size)
{
List<ScheduledShow> shows = new List<ScheduledShow>();
Database db = DatabaseFactory.CreateDatabase("TVScheduleSqlServer");
DbCommand cmd = db.GetStoredProcCommand("sp_get_YTVDayShowlist");
db.AddInParameter(cmd, "#CurrentDay", DbType.DateTime, date);
IDataReader reader = db.ExecuteReader(cmd);
int i = 0;
while (reader.Read() && (i < size || size == -1))
{
ScheduledShow show = new ScheduledShow();
show.AirTime = Convert.ToDateTime(reader["Airing_datetime"].ToString());
show.StationId = Convert.ToInt32(reader["Station_id"].ToString());
show.ScheduleRowId = Convert.ToInt32(reader["id"].ToString());
show.StoryLine = reader["StoryLine"].ToString();
show.Title = reader["Title_name"].ToString();
show.SimsTitleId = Convert.ToInt32(reader["Sims_title_id"].ToString());
show.ProgramId = Convert.ToInt32(reader["Program_id"].ToString());
show.Genre = reader["Genre_list"].ToString();
show.ProgramName = reader["program_name"].ToString();
show.ShowUrl = reader["ShowURL"].ToString();
show.CssClass = reader["CSSCLASS"].ToString();
shows.Add(show);
i++;
}
reader.Close();
reader.Dispose();
return shows;
}
static public string SerializeToXML(List<ScheduledShow> shows)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<ScheduledShow>), new XmlRootAttribute("ScheduledShows"));
//StringWriter stringWriter = new StringWriter();
string xml;
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
{
serializer.Serialize(xmlTextWriter, shows);
using (MemoryStream memoryStream2 = (MemoryStream)xmlTextWriter.BaseStream)
{
xml = UTF8ByteArrayToString(memoryStream2.ToArray());
}
}
}
return xml;
}
/// <summary>
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
/// </summary>
/// <param name="characters">Unicode Byte Array to be converted to String</param>
/// <returns>String converted from Unicode Byte Array</returns>
private static String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}
}
}
ScheduledShow.cs
using System;
using System.Xml.Serialization;
namespace CommunityServer.Scheduler
{
[XmlRoot("ScheduledShowElement")]
public class ScheduledShow
{
[XmlElement("AirTime")]
public DateTime AirTime
{ get; set; }
[XmlElement("StationId")]
public int StationId
{ get; set; }
[XmlElement("ScheduleRowId")]
public int ScheduleRowId
{ get; set; }
[XmlElement("StoryLine")]
public string StoryLine
{ get; set; }
[XmlElement("Title")]
public string Title
{ get; set; }
[XmlElement("ProgramId")]
public int ProgramId
{ get; set; }
[XmlElement("Genre")]
public string Genre
{ get; set; }
[XmlElement("ProgramName")]
public string ProgramName
{ get; set; }
[XmlElement("SimsTitleId")]
public int SimsTitleId
{ get; set; }
[XmlElement("ShowUrl")]
public string ShowUrl
{ get; set; }
[XmlElement("CssClass")]
public string CssClass
{ get; set; }
}
}
Output of the xml file
<?xml version="1.0" encoding="utf-8"?>
<ScheduledShows xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ScheduledShow>
<AirTime xmlns="http://example.books.com">2009-09-17T10:20:00</AirTime>
<StationId xmlns="http://example.books.com">770</StationId>
<ScheduleRowId xmlns="http://example.books.com">17666100</ScheduleRowId>
<StoryLine xmlns="http://example.books.com">When Dooley demonstrates his newest hobby, magic, Willa gets an idea. A huge backyard magic show! Starring the Great Doolini and his amazing disappearing elephant trick! Unfortunately, Lou the elephant misunderstands and thinks Willa wants him to disappear for real. In the middle of the show Willa must find Lou and apologize so he&rsquo;ll reappear! / When the animals and Willa discover an egg in their backyard, their parental propriety kicks in. Especially when Dooley relates a factoid about young hatchlings imprinting on the first critter they see. Willa&rsquo;s critters vie for egg watching rights, so they can be first to be called Mama! Or Poppa!</StoryLine>
<Title xmlns="http://example.books.com">Disappearing Act / Great Eggspectations</Title>
<ProgramId xmlns="http://example.books.com">2202</ProgramId>
<Genre xmlns="http://example.books.com">Animated</Genre>
<ProgramName xmlns="http://example.books.com">Willa's Wild Life</ProgramName>
<SimsTitleId xmlns="http://example.books.com">68914</SimsTitleId>
<ShowUrl xmlns="http://example.books.com">willas_wildlife</ShowUrl>
<CssClass xmlns="http://example.books.com">none</CssClass>
</ScheduledShow>
<ScheduledShow>
<AirTime xmlns="http://example.books.com">2009-09-17T10:45:00</AirTime>
<StationId xmlns="http://example.books.com">770</StationId>
<ScheduleRowId xmlns="http://example.books.com">17666105</ScheduleRowId>
<StoryLine xmlns="http://example.books.com">It&rsquo;s Club Day in Gloomsville. The gang splinter off to form clubs and prepare for the club&rsquo;s appearance in the big Gloomsville parade. Skull Boy forms the coolest club of all with some new jazzy skeletal friends that no one ever sees. At first no one believes Skull Boy has these new friends since every time they want to meet them, they disappear. When pressed for details, she admits she hasn&rsquo;t met them yet &ndash; they&rsquo;re imaginary. </StoryLine>
<Title xmlns="http://example.books.com">Skull Boys Don't Cry</Title>
<ProgramId xmlns="http://example.books.com">1418</ProgramId>
<Genre xmlns="http://example.books.com">Animated</Genre>
<ProgramName xmlns="http://example.books.com">Ruby Gloom</ProgramName>
<SimsTitleId xmlns="http://example.books.com">54297</SimsTitleId>
<ShowUrl xmlns="http://example.books.com">rubygloom</ShowUrl>
<CssClass xmlns="http://example.books.com">none</CssClass>
</ScheduledShow>
<ScheduledShow>
<AirTime xmlns="http://example.books.com">2009-09-17T11:10:00</AirTime>
<StationId xmlns="http://example.books.com">770</StationId>
<ScheduleRowId xmlns="http://example.books.com">17666113</ScheduleRowId>
<StoryLine xmlns="http://example.books.com">When Mad Margaret gets trapped in a jar she becomes a source of entertainment for Erky./Erky and Perky need a place to live and who better to find it for them than Frenzel.</StoryLine>
<Title xmlns="http://example.books.com">Erky's Birthday / Location Location Location</Title>
<ProgramId xmlns="http://example.books.com">1347</ProgramId>
<Genre xmlns="http://example.books.com">Animated</Genre>
<ProgramName xmlns="http://example.books.com">Erky Perky</ProgramName>
<SimsTitleId xmlns="http://example.books.com">49009</SimsTitleId>
<ShowUrl xmlns="http://example.books.com">erky_perky</ShowUrl>
<CssClass xmlns="http://example.books.com">none</CssClass>
</ScheduledShow>
<ScheduledShow>
<AirTime xmlns="http://example.books.com">2009-09-17T11:35:00</AirTime>
<StationId xmlns="http://example.books.com">770</StationId>
<ScheduleRowId xmlns="http://example.books.com">17666116</ScheduleRowId>
<StoryLine xmlns="http://example.books.com">SYNOPSIS:The Joyco toy company has heard about George and his Zoopercar and they want to market it as their newest toy. But George isn't interested in selling his prized mode of transportation. Afterall, he and his Dad built it together and no one can take that special bond away from him. But two Joyco toy employees, Barry and Steve, have other plans. If George won't sell it to them, they will just have to take it, which they do. But once their boss, Big Ed Easy finds out that George has be</StoryLine>
<Title xmlns="http://example.books.com">ZOOPERCAR CAPER</Title>
<ProgramId xmlns="http://example.books.com">311</ProgramId>
<Genre xmlns="http://example.books.com" />
<ProgramName xmlns="http://example.books.com">George Shrinks</ProgramName>
<SimsTitleId xmlns="http://example.books.com">25371</SimsTitleId>
<ShowUrl xmlns="http://example.books.com" />
<CssClass xmlns="http://example.books.com">none</CssClass>
</ScheduledShow>
<ScheduledShow>
<AirTime xmlns="http://example.books.com">2009-09-17T11:35:00</AirTime>
<StationId xmlns="http://example.books.com">770</StationId>
<ScheduleRowId xmlns="http://example.books.com">17666116</ScheduleRowId>
<StoryLine xmlns="http://example.books.com">SYNOPSIS:The Joyco toy company has heard about George and his Zoopercar and they want to market it as their newest toy. But George isn't interested in selling his prized mode of transportation. Afterall, he and his Dad built it together and no one can take that special bond away from him. But two Joyco toy employees, Barry and Steve, have other plans. If George won't sell it to them, they will just have to take it, which they do. But once their boss, Big Ed Easy finds out that George has be</StoryLine>
<Title xmlns="http://example.books.com">ZOOPERCAR CAPER</Title>
<ProgramId xmlns="http://example.books.com">311</ProgramId>
<Genre xmlns="http://example.books.com" />
<ProgramName xmlns="http://example.books.com">George Shrinks</ProgramName>
<SimsTitleId xmlns="http://example.books.com">25371</SimsTitleId>
<ShowUrl xmlns="http://example.books.com">george_shrinks</ShowUrl>
<CssClass xmlns="http://example.books.com">none</CssClass>
</ScheduledShow>
</ScheduledShows>
I found an answer to my question here:
http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/4b228734-a209-445a-991c-0420b381ac93
I just used [XmlType("")] and that worked.
using System;
using System.Xml.Serialization;
namespace CommunityServer.Scheduler
{
[XmlType("ScheduledShowElement")]
public class ScheduledShow
{
...
}
}
[XmlRoot(...)] only affects the outermost element (<ScheduledShows>...</ScheduledShows>). I suspect you want [XmlElement(...)]. Of course, another way is to write an object wrapper:
[XmlRoot("SheduledShows")]
public class Shows {
[XmlElement("SheduledShowElement")]
public List<Show> Shows {get;set;}
}
And serialize this wrapper object instead of just a list.
You need to use the overloaded constructor that takes in a XmlAttributeOverrides and make sure you override the name of the ScheduledShow class.
I also used XmlType attribute [XmlType("")] and worked.
[XmlRoot] and [XmlType] are only available for classes.
[XmlElement] are only for properties.
See this: https://learn.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes#controlling-serialization-of-classes-using-xmlrootattribute-and-xmltypeattribute

Categories

Resources