如何添加一个命名空间,在做XmlSerialization用的XmlWriter? [英] How do I add a namespace while doing XmlSerialization with an XmlWriter?

查看:225
本文介绍了如何添加一个命名空间,在做XmlSerialization用的XmlWriter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的与XML序列化相结合的的XmlWriter。我能够输出XML很好,但如何将xmlns属性与的XmlWriter似乎是逃避我。

要写出我用下面的文件的开头:

  Writer.WriteStartDocument();
    Writer.WriteStartElement(urlset,http://www.sitemaps.org/schemas/sitemap/0.9);
 

随着我的XmlWriter通过SitemapNodes创建我然后循环我已经创造了他们,并通过序列化这样写到底层StringBuilder的:

 的foreach(在列表uk.co.andrewrea.SitemapNode节点)
    {
        Serializer.Serialize(作家,节点);
    }
 

正如我说,这工作正常,但不包括根元素上面的命名空间。每次我试着写物理属性,XMLNS,我得到一个异常的的xmlns由系统对XML的使用而保留的,所以基本上无法使用。

我知道如何使用XmlTextWriter对象,并使用XmlDocument类要做到这一点,但我需要了解我是如何使用的XmlWriter,并通过序列化实现这一目标。

下面的尝试也抛出异常有关的命名空间被保留。

 的foreach(在列表uk.co.andrewrea.SitemapNode节点)
{
      XmlSerializerNamespaces NS =新XmlSerializerNamespaces();
      ns.Add(的xmlns,http://www.sitemaps.org/schemas/sitemap/0.9);

      Serializer.Serialize(作家,节点,NS);
}

异常详细信息:System.ArgumentException:preFIX的xmlns是由XML保留。
 

解决方案

您可以添加命名空间到XmlSerialization属性,如:

  [的XmlElement(
的ElementName =成员,
命名空间=htt​​p://www.cpandl.com)]
公务员[]员工;
 

如果您在code控制。

I am using the XmlWriter in conjunction with Xml Serialization. I am able to output the XML fine, but how to include the xmlns attribute with the XmlWriter seems to be escaping me.

To write the start of the document I use the following:

    Writer.WriteStartDocument();
    Writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");

With my XmlWriter created I then loop through SitemapNodes I have created them and write them to the underlying stringbuilder through serialization like this:

    foreach (uk.co.andrewrea.SitemapNode node in List)
    {
        Serializer.Serialize(Writer, node);
    }

As I say this works fine BUT the above namespace for the root element is not included. Every time I try to physically write the attribute, xmlns, I get an exception that the xmlns is reserved by the system for XML use, so basically I cannot use.

I know how to do this using the XmlTextWriter and also using the XmlDocument class but i need to understand how I achieve this using the XmlWriter and through Serialization.

The following attempt also throws the exception about that namespace being reserved.

foreach (uk.co.andrewrea.SitemapNode node in List)
{
      XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
      ns.Add("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

      Serializer.Serialize(Writer, node, ns);
}

Exception Details: System.ArgumentException: Prefix "xmlns" is reserved for use by XML.

解决方案

You can add the namespace to the XmlSerialization attributes, e.g.:

[XmlElement(
ElementName = "Members",
Namespace = "http://www.cpandl.com")]
public Employee[] Employees;

if you have control over the code.

这篇关于如何添加一个命名空间,在做XmlSerialization用的XmlWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆