【问题标题】:Remove xmlns attribute from elements when generating XML with LINQ?使用 LINQ 生成 XML 时从元素中删除 xmlns 属性?
【发布时间】:2023-03-24 02:59:01
【问题描述】:

我有一个关于生成sitemap.xml的问题

我的创作者代码是这样的:

XNamespace xmlns = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");
XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
XNamespace schemaLocation = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

XElement urlset = new XElement(xmlns+"urlset",
                  new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                  new XAttribute(xsi + "schemaLocation", schemaLocation));       

urlset.Add(new XElement("url"));

此代码生成 xml 文件,但生成的 sitemap.xml url 元素包含 xmlns="" 属性。

<urlset xmlns="..." ><url xmlns=""/> </urlset>

所有&lt;url&gt; 元素都包含xmlns = "" 属性。

我该如何解决这个问题?

【问题讨论】:

  • 你能显示你添加Url的代码吗?
  • 如果您要像 urlset.Add ( new XElement ( xmlns + "Url" ) ); 这样添加您的 Url 节点,那么您将不会得到空的命名空间属性......或者至少我没有
  • 我编辑了那个 urlset.Add(new XElement("url"));
  • 如果 url 和 urlset 都属于同一个命名空间,则您限定 urlset,xmlns+"urlset" 但不是 url

标签: c# xml linq linq-to-xml


【解决方案1】:

我认为W3 Org 可以比我更好地总结命名空间,您对“url”节点上方的所有节点和属性都有合格的命名空间。当您添加urlset.Add(new XElement("url")); 时,它应该如何确定它所在的命名空间?

我建议您尝试一下,看看它对您有什么作用:

static void Main ( string [] args )
{
    XNamespace xmlns = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");
    XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
    XNamespace schemaLocation = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

    XElement urlset = new XElement(xmlns+"urlset",
               new XAttribute(XNamespace.Xmlns + "xsi", xsi),
               new XAttribute(xsi + "schemaLocation", schemaLocation));       

    urlset.Add(new XElement(xmlns+"url")); // NB> We are qualifying the node
    var s = urlset.ToString( );
    Console.ReadKey( );
}

【讨论】:

    【解决方案2】:

    试试这个代码

    XmlDocument stripDocumentNamespace(XmlDocument oldDom)
    {
        XmlDocument newDom = new XmlDocument();
        newDom.LoadXml(Regex.Replace(oldDom.OuterXml,
             @"(xmlns:?[^=]*=[""][^""]*[""])", "",
             RegexOptions.IgnoreCase | RegexOptions.Multiline));
        return newDom;
    } 
    

    【讨论】:

    • 我能理解为什么正则表达式是处理 XML 的坏习惯吗?谢谢。
    • 非常简单地说,正则表达式匹配 CS 中所谓的“常规语言”。 XML 不是常规语言(HTML 也不是)。正则表达式无法匹配所有 XML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多