使用XmlWriter

时间:2016-05-23 12:22:02

标签: c# asp.net xml xmlwriter

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

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:前缀''无法在同一个start元素标记内从''重新定义为'http://www.sitemaps.org/schemas/sitemap/0.9'。

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

  

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

有人有任何想法吗?我认为没有理由发生这种情况。

1 个答案:

答案 0 :(得分: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的开头