从.NET中的XmlDocument生成XML时,xmlns
第一次插入没有关联命名空间的元素时会出现空白属性.怎么能防止这种情况?
例:
XmlDocument xml = new XmlDocument();
xml.AppendChild(xml.CreateElement("root",
"whatever:name-space-1.0"));
xml.DocumentElement.AppendChild(xml.CreateElement("loner"));
Console.WriteLine(xml.OuterXml);
Run Code Online (Sandbox Code Playgroud)
输出:
<root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root>
Run Code Online (Sandbox Code Playgroud)
期望的输出:
<root xmlns="whatever:name-space-1.0"><loner /></root>
Run Code Online (Sandbox Code Playgroud)
是否有适用于XmlDocument
代码的解决方案,而不是在将文档转换为字符串后出现的问题OuterXml
?
我这样做的原因是看看我是否可以使用XmlDocument生成的XML匹配特定协议的标准XML.空白xmlns
属性可能不会破坏或混淆解析器,但它在我已经看到的此协议的任何用法中也不存在.
我有这个代码:
function setupProject($projectFile) {
[xml]$root = Get-Content $projectFile;
$project = $root.Project;
$beforeBuild = $root.CreateElement("Target", "");
$beforeBuild.SetAttribute("name", "BeforeBuild");
$beforeBuild.RemoveAttribute("xmlns");
$project.AppendChild($beforeBuild);
$root.Save($projectFile);
}
Run Code Online (Sandbox Code Playgroud)
它应该<Target name="BeforeBuild" />
为XML文档添加一个新内容.
但它也添加了一个xmlns=""
我不想要的空属性.(它实际上是Visual Studio,它不喜欢这个属性!)
<Target name="BeforeBuild" xmlns="" />
Run Code Online (Sandbox Code Playgroud)
我已经尝试过这段代码:
$beforeBuild.RemoveAttribute("xmlns");
$project.AppendChild($beforeBuild);
$beforeBuild.RemoveAttribute("xmlns");
Run Code Online (Sandbox Code Playgroud)