I want to use the RSS2 extensions feature to add my own non-standard elements to my RSS feed as described here:
http://cyber.law.harvard.edu/rss/rss.html#extendingRss:
However I don't think that the .Net Rss20FeedFormatter class supports this feature.
My code looks something like this:
public Rss20FeedFormatter GetRSS()
{
var feed = new SyndicationFeed(....);
feed.Items = new List<SyndicationItem>();
// add items to feed
return new Rss20FeedFormatter(feed);
}
If it doesn't support it is there any alternative to just creating the XML element by element?
Here's my findings. Took me a while to figure it all out.
This is what you do, your feed has to have a namespace
XNamespace extxmlns = "http://www.yoursite.com/someurl";
feed.AttributeExtensions.Add(new XmlQualifiedName("ext", XNamespace.Xmlns.NamespaceName), extxmlns.NamespaceName);
feed.ElementExtensions.Add(new XElement(extxmlns + "link", new XAttribute("rel", "self"), new XAttribute("type", "application/rss+xml")));
return new Rss20FeedFormatter(feed, false);
Your items need to be a derived class, and you write the extended properties in WriteElementExtensions, making sure you prefix them with the namespace (you don't have to but this is what is required to make it valid RSS).
class TNSyndicationItem : SyndicationItem
protected override void WriteElementExtensions(XmlWriter writer, string version)
{
writer.WriteElementString("ext:abstract", this.Abstract);
writer.WriteElementString("ext:channel", this.Channel);
}
The extended properties are ignore if you look in an RSS reader such as firefox, you'll need to write code to read them as well.
The url http://www.yoursite.com/someurl doesn't have to exist, but you need it to define the namespace and make the RSS valid. Normally you'll just put a page there which says something about what the feed should look like.
Related
I need to read some XML files that follow the ONIX standard
See: http://www.editeur.org/93/Release-3.0-Downloads/
To do this i downloaded the ONIX 3.0 XSD:
http://www.editeur.org/files/ONIX%203/ONIX_BookProduct_XSD_schema+codes_Issue_25.zip
Using the downloaded XSD and this command "xsd your.xsd /classes" i created classes that i want to use.
When trying to create a new Xml Serializer like so:
var xmls = new XmlSerializer(typeof(Model.ONIX.editeur.ONIXMessage));
I get and exception
"There was an error reflecting type 'Model.ONIX.editeur.ONIXMessage'."
When i drill down through the inner exceptions i end up with this message:
"{"Member 'Text' cannot be encoded using the XmlText attribute. You
may use the XmlText attribute to encode primitives, enumerations,
arrays of strings, or arrays of XmlNode."}"
I am not sure what to do, is something wrong with the XSD? Any suggestions?!
Edit
public static List<Model.ONIX.editeur.Product> GetProductsDataFromOnixFile(string onixFileLocation)
{
var xmls = new XmlSerializer(typeof(Model.ONIX.editeur.ONIXMessageRefname));
using (var reader = XmlReader.Create(onixFileLocation))
{
if (xmls.CanDeserialize(reader))
{
var onixMessage = (Model.ONIX.editeur.ONIXMessage)xmls.Deserialize(reader);
return onixMessage.Items.OfType<Model.ONIX.editeur.Product>().ToList();
}
throw new Exception(string.Format("Cant read the file {0} as Onix", onixFileLocation));
}
}
I know this question is old but I assume others with specific Onix issues will run into this.
Here is how I got it to work.
In the reference xsd are two includes in the top. Here I copy/pasted the other two files in.
<xs:include schemaLocation="ONIX_BookProduct_CodeLists.xsd" />
<xs:include schemaLocation="ONIX_XHTML_Subset.xsd" />
I.e. these lines are replaced in the file with the corresponding file.
Then I did the
xsd ONIX_BookProduct_3.0_reference.xsd /classes
And then it generates the .cs file. And the only issue I had here was I had to remove a text attribute from all fields that was e.g. List147, but not from the fields that was string. E.g. I had to remove the attribute from generated code like this:
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public List121 textscript {
get {
return this.textscriptField;
but not from attributes like this
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
I Know I'm able to pipe out/in using simple Console.WriteLine and Console.ReadLine methods, but that way I'm passing a string between processes (which must be parsed to recreate the object).
What I'm wondering is if I would be able to pipe my own types, so that I could retrieve them easily in destiny process. What I expect is to do something like:
myProgram | get-member
And the output would something like MyNameSpace.MyType and the list of its members (currently it shows the typeName System.String)
Is that possible in a console app or could I only achieve this using cmdlets?
The easiest way to do this is to use serialization to turn the objects you wish to send from one to the other into a pipeable format to send them from one to the other. There are, however, a number of constraints on doing this:
First, the implementation of the types you're passing back and forth have to be available to all the apps that may handle them. (That's not a problem for PowerShell because all the cmdlets run inside the same process.) So the easiest way to do this is to create the types you're going to pipe around inside a class library that's referenced by all the console apps. This class, for example, I put in my sample shared library:
[Serializable]
public class TestClass
{
public string Test { get; set; }
public string TestAgain { get; set; }
public string Cheese { get; set; }
}
The [Serializable] attribute marks it as serializable, which is sufficient for simple classes. For more complex classes, more may be required - see MSDN, starting here: http://msdn.microsoft.com/en-us/library/4abbf6k0(v=VS.71).aspx
Then, in the program you're piping from, you serialize it to XML and write it out to console like this:
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Shared;
namespace Out
{
class Program
{
static void Main(string[] args)
{
// Create the object.
TestClass test = new TestClass();
test.Test = "Monkey";
test.TestAgain = "Hat";
test.Cheese = "Fish";
// Serialize it.
XmlSerializer serializer = new XmlSerializer(typeof (TestClass));
StringBuilder sb = new StringBuilder();
using (var writer = new StringWriter(sb))
serializer.Serialize(writer, test);
// And write it to console.
Console.WriteLine(sb.ToString());
}
}
}
When run, this outputs the instance's properties encoded in XML, thus:
<?xml version="1.0" encoding="utf-16"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http
://www.w3.org/2001/XMLSchema">
<Test>Monkey</Test>
<TestAgain>Hat</TestAgain>
<Cheese>Fish</Cheese>
</TestClass>
Then, in your receiving application, you reverse the process, reading from the console, thus:
using System;
using System.IO;
using System.Xml.Serialization;
using Shared;
namespace In
{
class Program
{
static void Main(string[] args)
{
// Read the input XML; until complete.
string input = Console.In.ReadToEnd();
TestClass passedIn;
// Deserialize it.
var serializer = new XmlSerializer(typeof (TestClass));
using (var reader = new StringReader(input))
passedIn = (TestClass) serializer.Deserialize(reader);
// Do something with the object.
Console.WriteLine("Test: {0}", passedIn.Test);
Console.WriteLine("TestAgain: {0}", passedIn.TestAgain);
Console.WriteLine("Cheese: {0}", passedIn.Cheese);
}
}
}
And voila!
C:\Working\PipeExample\In\bin\Debug>..\..\..\Out\bin\Debug\Out.exe | in
Test: Monkey
TestAgain: Hat
Cheese: Fish
You'll need some additional code, of course, to make sure that the receiving application knows what type(s) to expect - or can handle anything it gets - and since the intermediate XML is not very human-parsable, you'll need a way to make sure that the sending application knows when it's talking to a pipe and when it's talking to a human. In .NET 4.5, the Console.IsOutputRedirected() method will do that for you ( http://msdn.microsoft.com/en-us/library/system.console.isoutputredirected%28v=VS.110%29.aspx ), but in earlier versions, there's not an easy way to get at this information programmatically.
But this is the core of the thing, and looking at the documentation for and around XmlSerializer should give you the rest.
Why don't you write your own cmdlet instead of a console program?
A PowerShell module can be a binary module (a DLL assembly) composed by cmdlets writen in C#. Have a look to Installing the Windows PowerShell SDK.
I am using the .NET XmlSerializer class to deserialize GPX files.
There are two versions of the GPX standard:
<gpx xmlns="http://www.topografix.com/GPX/1/0"> ... </gpx>
<gpx xmlns="http://www.topografix.com/GPX/1/1"> ... </gpx>
Also, some GPX files do not specify a default namespace:
<gpx> ... </gpx>
My code needs to handle all three cases, but I can't work out how to get XmlSerializer to do it.
I am sure there must be a simple solution because this a common scenario, for example KML has the same issue.
I have done something similar to this a few times before, and this might be of use to you if you only have to deal with a small number of namespaces and you know them all beforehand. Create a simple inheritance hierarchy of classes, and add attributes to the different classes for the different namespaces. See the following code sample. If you run this program it gives the output:
Deserialized, type=XmlSerializerExample.GpxV1, data=1
Deserialized, type=XmlSerializerExample.GpxV2, data=2
Deserialized, type=XmlSerializerExample.Gpx, data=3
Here is the code:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
[XmlRoot("gpx")]
public class Gpx {
[XmlElement("data")] public int Data;
}
[XmlRoot("gpx", Namespace = "http://www.topografix.com/GPX/1/0")]
public class GpxV1 : Gpx {}
[XmlRoot("gpx", Namespace = "http://www.topografix.com/GPX/1/1")]
public class GpxV2 : Gpx {}
internal class Program {
private static void Main() {
var xmlExamples = new[] {
"<gpx xmlns='http://www.topografix.com/GPX/1/0'><data>1</data></gpx>",
"<gpx xmlns='http://www.topografix.com/GPX/1/1'><data>2</data></gpx>",
"<gpx><data>3</data></gpx>",
};
var serializers = new[] {
new XmlSerializer(typeof (Gpx)),
new XmlSerializer(typeof (GpxV1)),
new XmlSerializer(typeof (GpxV2)),
};
foreach (var xml in xmlExamples) {
var textReader = new StringReader(xml);
var xmlReader = XmlReader.Create(textReader);
foreach (var serializer in serializers) {
if (serializer.CanDeserialize(xmlReader)) {
var gpx = (Gpx)serializer.Deserialize(xmlReader);
Console.WriteLine("Deserialized, type={0}, data={1}", gpx.GetType(), gpx.Data);
}
}
}
}
}
Here's the solution I came up with before the other suggestions came through:
var settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreProcessingInstructions = true;
settings.IgnoreWhitespace = true;
using (var reader = XmlReader.Create(filePath, settings))
{
if (reader.IsStartElement("gpx"))
{
string defaultNamespace = reader["xmlns"];
XmlSerializer serializer = new XmlSerializer(typeof(Gpx), defaultNamespace);
gpx = (Gpx)serializer.Deserialize(reader);
}
}
This example accepts any namespace, but you could easily make it filter for a specific list of known namespaces.
Oddly enough you can't solve this nicely. Have a look at the deserialize section in this troubleshooting article. Especially where it states:
Only a few error conditions lead to exceptions during the
deserialization process. The most common ones are:
•The name of the
root element or its namespace did not match the expected name.
...
The workaround I use for this is to set the first namespace, try/catch the deserialize operation and if it fails because of the namespace I try it with the next one. Only if all namespace options fail do I throw the error.
From a really strict point of view you can argue that this behavior is correct since the type you deserialize to should represent a specific schema/namespace and then it doesn't make sense that it should also be able to read data from another schema/namespace. In practice this is utterly annoying though. File extenstion rarely change when versions change so the only way to tell if a .gpx file is v0 or v1 is to read the xml contents but the xmldeserializer won't unless you tell upfront which version it will be.
I was using a certain method for parsing my app.config file. Then I was told that using ConfigurationManager is better and simpler. But the thing is I don't know how to do it with ConfigurationManager.
My original code looked like this:
XmlNode xmlProvidersNode;
XmlNodeList xmlProvidersList;
XmlNodeList xmlTaskFactoriesList;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("app.config");
xmlProvidersNode = xmlDoc.DocumentElement.SelectSingleNode("TaskProviders");
xmlProvidersList = xmlProvidersNode.SelectNodes("TaskProvider");
foreach (XmlNode xmlProviderElement in xmlProvidersList)
{
if (xmlProviderElement.Attributes.GetNamedItem("Name").Value.Equals(_taskProvider))
{
xmlTaskFactoriesList = xmlProviderElement.SelectNodes("TaskTypeFactory");
foreach (XmlNode xmlTaskFactoryElement in xmlTaskFactoriesList)
{
if (xmlTaskFactoryElement.Attributes.GetNamedItem("TaskType").Value.Equals(_taskType))
{
taskTypeFactory = xmlTaskFactoryElement.Attributes.GetNamedItem("Class").Value;
}
}
}
}
What would be the equivalent using ConfigurationManager? (Because all I can see is how to get keys not nodes..)
Thanks
Create a class that inherits ConfigurationSection called, say, MyConfigSection. Then you can use the ConfigurationManager.GetSection method to get an instance of your MyConfigSection class. The ConfigurationManager will do all the parsing, so you will have a strongly typed object to work with. Here is an excellent example to follow.
If you are concerned about the custom sections create your own class using Configuration section class. Here is an example about using it.
I'm trying to serialize a custom class that needs to use multiple elements of the same name.
I've tried using xmlarray, but it wraps them in another elements.
I want my xml to look like this.
<root>
<trees>some text</trees>
<trees>some more text</trees>
</root>
My code:
[Serializable(), XmlRoot("root")]
public class test
{
[XmlArray("trees")]
public ArrayList MyProp1 = new ArrayList();
public test()
{
MyProp1.Add("some text");
MyProp1.Add("some more text");
}
}
Try just using [XmlElement("trees")]:
[Serializable(), XmlRoot("root")]
public class test
{
[XmlElement("trees")]
public List<string> MyProp1 = new List<string>();
public test()
{
MyProp1.Add("some text");
MyProp1.Add("some more text");
}
}
Note I changed ArrayList to List<string> to clean up the output; in 1.1, StringCollection would be another option, although that has different case-sensitivity rules.
(edit: obsoleted - my second post ([XmlElement]) is the way to go - I'm leaving this for posterity in using xsd.exe)
xsd.exe is your friend. Copy the xml you want into a file (foo.xml), then use:
xsd foo.xml
xsd foo.xsd /classes
Now read foo.cs; you can use this either directly, or just for inspiration.
(edit: output snipped - not helpful any more)