.NET XmlWriter中的正确名称空间管理 [英] Proper name space management in .NET XmlWriter

查看:41
本文介绍了.NET XmlWriter中的正确名称空间管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在工作中广泛使用.NET XML技术.我非常喜欢的一件事是XSLT引擎,更确切地说是它的可扩展性.然而,有一点点不停地成为烦恼的源头.没什么大不了的,或者我们不能忍受的东西,但是它阻止了我们产生我们想要产生的漂亮的XML.

I use .NET XML technologies quite extensively on my work. One of the things the I like very much is the XSLT engine, more precisely the extensibility of it. However there one little piece which keeps being a source of annoyance. Nothing major or something we can't live with but it is preventing us from producing the beautiful XML we would like to produce.

我们要做的一件事是内联转换节点并将节点从一个XML文档导入到另一个XML文档.

One of the things we do is transform nodes inline and importing nodes from one XML document to another.

可悲的是,当您将节点保存到 XmlTextWriter (实际上是任何 XmlWriter.Create(Stream)返回的内容)时,无论将其命名空间定义都扔到那里是否必要(先前定义).您得到以下xml的一种:

Sadly , when you save nodes to an XmlTextWriter (actually whatever XmlWriter.Create(Stream) returns), the namespace definitions get all thrown in there, regardless of it is necessary (previously defined) or not. You get kind of the following xml:

<root xmlns:abx="http://bladibla">  
     <abx:child id="A">  
         <grandchild id="B">
             <abx:grandgrandchild xmlns:abx="http://bladibla" />  
         </grandchild>  
     </abx:child>  
</root>

有人对如何说服.NET有效地命名空间定义提出建议吗?

Does anyone have a suggestion as to how to convince .NET to be efficient about its namespace definitions?

PS.另外,我想覆盖默认的名称空间,在编写节点时对其进行更改.

PS. As an added bonus I would like to override the default namespace, changing it as I write a node.

推荐答案

使用以下代码:

using (var writer = XmlWriter.Create("file.xml"))
{
    const string Ns = "http://bladibla";
    const string Prefix = "abx";

    writer.WriteStartDocument();

    writer.WriteStartElement("root");

    // set root namespace
    writer.WriteAttributeString("xmlns", Prefix, null, Ns);

    writer.WriteStartElement(Prefix, "child", Ns);
    writer.WriteAttributeString("id", "A");

    writer.WriteStartElement("grandchild");
    writer.WriteAttributeString("id", "B");

    writer.WriteElementString(Prefix, "grandgrandchild", Ns, null);

    // grandchild
    writer.WriteEndElement();
    // child
    writer.WriteEndElement();
    // root
    writer.WriteEndElement();

    writer.WriteEndDocument();
}

此代码产生了所需的输出:

This code produced desired output:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns:abx="http://bladibla">
  <abx:child id="A">
    <grandchild id="B">
      <abx:grandgrandchild />
    </grandchild>
  </abx:child>
</root>

这篇关于.NET XmlWriter中的正确名称空间管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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