在根元素中添加xml:space属性

7

我有一个小问题,本来以为它很简单...但是...

我有一些XML文件,我只想使用C#将xml:space="preserve"添加到根元素中。

我尝试了以下代码:

var rootElem = xDoc.Root; // XDocument
rootElem.SetAttributeValue("{xml}space", "preserve");

这样做的结果是:
<ProjectDetails xmlns="http://site/ppm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" p3:space="preserve" xmlns:p3="xml">

我认为这相当于

<ProjectDetails xmlns="http://site/ppm" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:space="preserve">

但是,由于xml:space是一个特殊属性,我有些疑虑。

那么:

它们是否相同?

有没有一种“清洁”的方法将其添加到文档中?

1个回答

11

你只需要正确的XName值 - 我会使用这个:

doc.Root.SetAttributeValue(XNamespace.Xml + "space", "preserve");

XName +(XNamespace, string) 操作符通常是我在使用LINQ to XML处理命名空间时最简单的方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接