在 XElement WriteTo 方法中,强制 XmlWriter 为具有定义的 xmlns 属性的子元素使用前缀

In XElement WriteTo method force XmlWriter to use a prefix for a child element with a defined xmlns attribute

我知道这个问题看起来与之前在这里提出的许多问题非常相似,但我找不到任何满意的答案。我将从外部提要中捕获的 rss 项目保存在数据库中,并且应该能够生成我自己的提要。考虑这段代码:

    [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);
            }
        }

我想得到的是

<content xmlns="http://search.yahoo.com/mrss/"> 

将在结果供稿中显示为

<media:content>

我不知道如何使用 XElement WriteTo(XmlWriter) 方法。

好的。我最终做了以下技巧: ...

//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();

...其余代码与问题中相同 从有问题的节点中删除 xmlns 属性已解决问题