添加没有命名空间的带前缀的起始元素

Add start element with prefix without namespace

有没有办法像这样在 XmlWriter 中使用 WriteStartElement 函数:

XmlWriter.WriteStartElement("prefix", "name", null);

Error occured: System.ArgumentException: 'Unable to use prefix with empty namespace.'

我不想在创建元素时设置名称空间 URI。
稍后我将通过 WriteAttributeString() 添加它,当其他属性将被创建时。

不,未绑定到命名空间 URI 的命名空间前缀没有意义,在 namespace-well-formed XML 文档中是不允许的。

I do not want to set namespace URI when creating element. Later on ill add it by WriteAttributeString(), when others attributes will be created.

前缀始终属于命名空间。通过定义非空命名空间,将自动创建 xmlns 属性:

writer.WriteStartElement("prefix", "localName", "ns"); // <prefix:localName xmlns:prefix="ns" />

我遇到了同样的问题,我一直在寻找解决方案,最终,我意识到我应该使用我已经定义的相同命名空间。

我有类似这样的东西来创建元素:

xmlWriter.WriteStartElement("xhtml", "link", "xmlns");

结果是:

<?xml version="1.0" encoding="utf-8" ?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://www.my-site.com/en/home</loc>
        <xhtml:link rel="alternative" hreflang="en" href="https://www.my-site.com/en/home" xmlns:xhtml="xmlns" />
        <xhtml:link rel="alternative" hreflang="ar" href="https://www.my-site.com/fr/home" xmlns:xhtml="xmlns" />
        <xhtml:link rel="alternative" hreflang="fa" href="https://www.my-site.com/fa/home" xmlns:xhtml="xmlns" />
    </url>
</urlset>

问题是我的 xhtml:link 元素正文中的 xmlns:xhtml="xmlns"

<xhtml:link rel="alternative" hreflang="en" href="https://www.my-site.com/en/home" xmlns:xhtml="xmlns" />

所以我把 http://www.w3.org/1999/xhtml 改为命名空间或 ns,如下所示:

xmlWriter.WriteStartElement("xhtml", "link", "http://www.w3.org/1999/xhtml");

现在它正是我需要的:

<?xml version="1.0" encoding="utf-8" ?>
<urlset xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://www.my-site.com/en/home</loc>
        <xhtml:link rel="alternative" hreflang="en" href="https://www.my-site.com/en/home" />
        <xhtml:link rel="alternative" hreflang="ar" href="https://www.my-site.com/fr/home" />
        <xhtml:link rel="alternative" hreflang="fa" href="https://www.my-site.com/fa/home" />
    </url>
</urlset>