I know that the question looks very similar to many asked here before, yet I could not find any satisfactory answers to it. I keep rss items captured from external feeds in a database and should be able to generate feeds of my own. Consider this code:
[Fact]
public void Test10() {
string item_xml =
"<item>\n"+
"<title>Item Title</title><link>http://example.com/news/somelink</link>\n"+
"<content url=\"https://s3.example.com/someorg/somemedia_5547_500x643_thmb.jpg\" xmlns=\"http://search.yahoo.com/mrss/\"></content>\n"+
"<contentType> releases </contentType>\n"+
"<pubDate> Thu, 06 Jun 2019 12:30:00 GMT </pubDate>"+
"</item>";
XElement xitem = XElement.Parse(item_xml);
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings() {
Indent = true, OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates
};
using (var sw = new StringWriter()) {
using (var writer = XmlWriter.Create(sw, xmlWriterSettings)) {
writer.WriteStartDocument();
writer.WriteStartElement("rss");
writer.WriteAttributeString("media", "http://www.w3.org/2000/xmlns/", "http://search.yahoo.com/mrss/");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("channel");
xitem.WriteTo(writer);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
string result = sw.ToString();
Assert.Contains("media:", result);
}
}
What I would like to get is that
<content xmlns="http://search.yahoo.com/mrss/">
would appear in the resulting feed as
<media:content>
I could not figure out how to do it using XElement WriteTo(XmlWriter) method.
Ok. I ended up doing a following trick: ...
//item_xml definition is not changed
XElement xitem = XElement.Parse(item_xml);
XNamespace ns = "http://search.yahoo.com/mrss/";
XElement mediacontent = xitem.Element(ns + "content");
mediacontent.Attribute("xmlns").Remove();
... the rest of the code is the same as in the question Removing the xmlns attribute from the node in question has solved the issue