【问题标题】:Write Multiple attributes to xml tag using XmlWriter [duplicate]使用 XmlWriter 将多个属性写入 xml 标签
【发布时间】:2016-05-23 12:22:01
【问题描述】:

正如标题所说,我正在尝试将多个属性写入一个标签,但是,我一直遇到错误:

writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
writer.WriteAttributeString("xsi", "schemaLocation", null, "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
writer.WriteAttributeString("xmlns", "xsi", "http://www.sitemaps.org/schemas/sitemap/0.9", "http://www.w3.org/2001/XMLSchema-instance");

是我正在使用的。

第一行给出了这个错误:

System.Xml.XmlException:前缀 '' 不能在同一起始元素标记内从 '' 重新定义为 'http://www.sitemaps.org/schemas/sitemap/0.9'。

如果你删除它,第三行会给出:

System.ArgumentException: 前缀“xmlns”保留给 XML 使用。

有人有什么想法吗?我看不出发生这种情况的原因。

【问题讨论】:

  • 我认为有一种特殊的方法可以添加命名空间......据我所知,这就像使用一些 NamespaceManager 之类的东西......谷歌它......
  • 您应该将默认命名空间传递给 WriteStartElement 方法。见C# XML - Multiple Namespace Declaration with XML Writer

标签: c# asp.net xml xmlwriter


【解决方案1】:

我认为没有理由发生这种情况

嗯,我愿意。第一个错误告诉您不能重新定义 xmlns 命名空间,因为它是指定 xml 命名空间的根元素的属性标记。

Xml 命名空间会自动解析(有点),我猜这就是你想要做的:

using (FileStream stream = new FileStream(@"C:\Temp\test.xml", FileMode.Create))
{
    XmlWriter x = new XmlTextWriter(stream, Encoding.UTF8);

    x.WriteStartElement("Root");
    x.WriteAttributeString("xmlns", "xsi", null, "http://www.sitemaps.org/schemas/sitemap/0.9");

    x.WriteStartElement("Element");
    x.WriteAttributeString("xsi", "schemaLocation", null, "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");
    x.WriteEndElement();

    x.WriteFullEndElement();
    x.Flush();
}

结果:

<Root xmlns:xsi="http://www.sitemaps.org/schemas/sitemap/0.9">
    <Element xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" />
</Root>

进一步的想法

如果您需要 "http://www.w3.org/2001/XMLSchema-instance" 显示为 xmlns,请将命名空间添加到 WriteStartElement 方法中,这将为您提供:

<Root xmlns:xsi="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns="http://www.w3.org/2001/XMLSchema-instance">

如果您需要 xml 声明,请像这样创建 XmlWriter

XmlWriterSettings settings = new XmlWriterSettings();
settings.NewLineHandling = NewLineHandling.None;
Settings.OmitXmlDeclaration = false;
XmlWriter x = XmlWriter.Create(stream, settings);

这将导致:

<?xml version="1.0" encoding="utf-8"?>

在您的 xml 开头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-15
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多