向现有的xml添加名称空间和别名 [英] Add namespace and alias to existing xml

查看:311
本文介绍了向现有的xml添加名称空间和别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码来更改BizTalk管道组件中现有XML消息中的名称空间.这行得通,但是我该如何向文档中添加名称空间别名.

I am using the code below to change a namespace in an existing XML message in a BizTalk pipeline component. This works but how would I add a namespace alias to the document as well.

XNamespace toNs = "http://hl7.org/fhir/Encounters";

XElement doc = XElement.Parse(xmlIn);

doc.DescendantsAndSelf().Attributes().Where(a => a.IsNamespaceDeclaration).Remove();

var ele = doc.DescendantsAndSelf();

foreach (var el in ele)
    el.Name = toNs +  el.Name.LocalName;

return new XDocument(doc);

推荐答案

您可以简单地在根目录中添加一个声明属性.举个例子:

You can simply add a declaration attribute to the root. Take this example:

<Root>
    <Child>Value</Child>
</Root>

如果运行此代码:

var root = XElement.Parse(xml);

XNamespace ns = "http://www.example.com/";

foreach (var element in root.DescendantsAndSelf())
{
    element.Name = ns + element.Name.LocalName;
}

root.Add(new XAttribute(XNamespace.Xmlns + "ex", ns));

您将得到以下结果:

<ex:Root xmlns:ex="http://www.example.com/">
  <ex:Child>Value</ex:Child>
</ex:Root>

有关演示,请参见此小提琴.

这篇关于向现有的xml添加名称空间和别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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