如何用C#替换xml里面的xmlns

问题描述 投票:0回答:2

我试图用 version 替换 xmlns 版本(任何版本) http://schemas.telerik.com/reporting/2012/3.6。在 C# 项目中

这是我得到的输入。

<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns="http://schemas.telerik.com/reporting/2012/4.0" 
        SnapGridSize="0.1cm" ShowSnapGrid="True" Name="NoviUgovor" Width="18.462cm">
</Report>

输入

xmlns
版本的Telerik报告是可变的。

这就是我想要得到的:

<?xml version="1.0" encoding="UTF-8"?>
<Report xmlns="http://schemas.telerik.com/reporting/2012/3.6" 
        SnapGridSize="0.1cm" ShowSnapGrid="True" Name="NoviUgovor" Width="18.462cm">
</Report>

输出

xmlns
版本的 Telerik 报告必须是

http://schemas.telerik.com/reporting/2012/3.6

这是项目里面的代码:

var doc = XDocument.Parse(rpt_dok);//rpt_dok (xml)
doc.Root.Attributes().Where(x => x.IsNamespaceDeclaration).Remove();
doc.Root.Add(new XAttribute("xmlns", "http://schemas.telerik.com/reporting/2012/3.6"));
rpt_dok = doc.ToString(); //error appears

我得到错误:

附加信息:不能将前缀“”从“http://schemas.telerik.com/reporting/2012/4.0”重新定义为“http://schemas.telerik.com/reporting/2012/3.6”开始元素标签。

我试过https://dotnetfiddle.net/qFuwWk但没有运气。

请帮忙!

c# xml linq-to-xml
2个回答
0
投票

您不必删除当前属性,它会被 SetAttributeValue 覆盖。

doc.Root.SetAttributeValue("xmlns", "http://schemas.telerik.com/reporting/2012/3.6"");


0
投票

我觉得最简单的方法就是固定一个xml的文本

rpt_dok = rpt_dok.Replace("http://schemas.telerik.com/reporting/2012/4.0", 
                             "http://schemas.telerik.com/reporting/2012/3.6");
© www.soinside.com 2019 - 2024. All rights reserved.