【问题标题】:In XElement WriteTo method force XmlWriter to use a prefix for a child element with a defined xmlns attribute在 XElement WriteTo 方法中,强制 XmlWriter 为具有已定义 xmlns 属性的子元素使用前缀
【发布时间】:2019-12-05 16:52:39
【问题描述】:

我知道这个问题看起来与之前在这里提出的许多问题非常相似,但我找不到任何令人满意的答案。我将从外部提要中捕获的 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) 方法。

【问题讨论】:

    标签: .net-core xml-namespaces prefix xelement xmlwriter


    【解决方案1】:

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

    //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 属性已解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2013-05-31
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      相关资源
      最近更新 更多