简体   繁体   English

XML命名空间前缀仅在根目录上

[英]XML Namespace prefix only on root

I am creating an XML document using the Task Factory XML Output Destination task though the output needs some tweaking and I can't seem to find a way to do this within the task so figured I would be able to do this via the script component with C#. 我正在使用“任务工厂XML输出目标”任务创建XML文档,尽管输出需要进行一些调整,而且我似乎找不到在任务中执行此操作的方法,因此我想我可以通过脚本组件使用C#。

This is the XML I am working with 这是我正在使用的XML

<?xml version="1.0" encoding="utf-8"?>
<CSDS xmlns="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
  <CYP000>
    <C000010>1.0</C000010>
  </CYP000>
</CSDS>

And I need to change the XML to look like: 而且我需要将XML更改为:

<?xml version="1.0" encoding="utf-8"?>
<CSDS:CSDS xmlns:CSDS="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
  <CYP000>
    <C000010>1.0</C000010>
  </CYP000>
</CSDS>

I have tried creating a new XDocument declaring the namespace and adding the source elements in but this adds the namespace to all elements. 我尝试创建一个新的XDocument来声明名称空间并在其中添加源元素,但这会将名称空间添加到所有元素中。

string xmlFile = @"C:\Temp\csds.xml";
string newXmlFile = @"C:\Temp\csds-new.xml";

XDocument sourceXml = XDocument.Load(xmlFile);
XNamespace ns = "http://www.datadictionary.nhs.uk/messages/CSDS-v1-0";
XDocument newXml = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement newRoot = new XElement(ns + "CSDS",
        new XAttribute(XNamespace.Xmlns + "CSDS", ns.NamespaceName));

newRoot.Add(sourceXml.Root.Elements());
newRoot.Save(newXmlFile);

Output 输出量

<?xml version="1.0" encoding="utf-8"?>
<CSDS:CSDS xmlns:CSDS="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
  <CSDS:CYP000>
    <CSDS:C000010>1.0</CSDS:C000010>
  </CSDS:CYP000>
</CSDS:CSDS>

I have found that doing the following after loading my file works along with the rest of my code: 我发现加载文件后执行以下操作与其余代码一起使用:

foreach (var descendants in sourceXml.Root.Descendants())
     descendants.Name = descendants.Name.LocalName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM