添加一个前缀的XML节点 [英] Adding a prefix to an xml node

查看:130
本文介绍了添加一个前缀的XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前文件格式

<Folio>
<Node1>Value1</Node1>
<Node2>Value2</Node2>
<Node3>Value3</Node3>
</Folio>



所需的输出

Desired Output

<vs:Folio>
<vs:Node1>Value1</vs:Node1>
<vs:Node2>Value2</vs:Node2>
<vs:Node3>Value3</vs:Node3>
</vs:Folio>



我使用的XmlElement和XmlDocument的到前缀添加到子节点元素,我无法完成它。我会很感激,如果有人能够给我在正确的方向向右推。

I am using XmlElement and XmlDocument to add the prefix to the child Node element and I'm unable to accomplish it. I would be really grateful if someone could give me the right push in the right direction.

推荐答案

如果您要添加的命名空间。向装载xml文档则是不可能的之后的元素

If you are trying to add namespace to the elements after loading the xml document then it is not possible.

从MSDN:

您不能添加,修改或
文件后XML文档的
例如删除
XML命名空间定义已被加载到XML
文档对象模型(XMLDOM)分析器。
是用来
的XML节点代表在XML文档中的数据是
时创建文档加载
插入XMLDOM分析器。当他们创建
这些节点
永久绑定到其XML
命名空间属性。因此,空XML
命名空间声明号(xmlns =)是附加到这些
节点的子节点,以保留这些节点的默认XML
命名空间属性

You cannot add, modify, or delete an XML namespace definition in an instance of an XML document after the document has been loaded into the XML Document Object Model (XMLDOM) parser. The XML nodes that are used to represent data in the XML document are created when the document is loaded into the XMLDOM parser. These nodes are permanently bound to their XML namespace attributes when they are created. Therefore, the empty XML namespace declaration (xmlns = "") is appended to the child nodes of these nodes to preserve the default XML namespace attribute of these nodes.

但是,您可以加载输入,读取每一个元素,并将其写入到另一个文档(或内存),其中有命名空间集中。
下面是解析字符串XML代码,创建了命名空间前缀和命名空间以及一个新的XML元素。

However you can load the input, read each element and write it to another document (or in-memory) which has the namespace set. Below is the code that parses the string xml, creates a new xml element along with namespace prefix and namespace.

            String xmlWithoutNamespace =
                @"<Folio><Node1>Value1</Node1><Node2>Value2</Node2><Node3>Value3</Node3></Folio>";
            String prefix ="vs";
            String testNamespace = "http://www.testnamespace/vs/";
            XmlDocument xmlDocument = new XmlDocument();

            XElement folio = XElement.Parse(xmlWithoutNamespace);
            XmlElement folioNode = xmlDocument.CreateElement(prefix, folio.Name.LocalName, testNamespace);

            var nodes = from node in folio.Elements()
                        select node;

            foreach (XElement item in nodes)
            {
                var node = xmlDocument.CreateElement(prefix, item.Name.ToString(), testNamespace);
                node.InnerText = item.Value;
                folioNode.AppendChild(node);
            }

            xmlDocument.AppendChild(folioNode);



XMLDOCUMENT现在包含与VS前缀每个节点的XML。

xmlDocument now contains the xml with each node prefixed with vs.

这篇关于添加一个前缀的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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