Com*_*eek 18 xml powershell dom appendchild
我有这个代码:
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)
Mic*_*Kay 24
添加了xmlns =""命名空间(un)声明,因为您的父元素位于命名空间中而您的子元素不在.如果您不希望添加此命名空间声明,则暗示您希望子元素与其父元素位于相同的命名空间中,答案是在创建元素时将其放在此命名空间中.也就是说,更改调用CreateElement("Target","")以指定正确的命名空间.
Neo*_*isk 12
检查这些可能的解决方案:
以下是适用于OP的第二个解决方案的解决方法:
$content = [xml] $content.OuterXml.Replace(" xmlns=`"`"", "")
$content.Save($_.FullName);
Run Code Online (Sandbox Code Playgroud)
正如Michael Kay回答的那样,删除此不需要的名称空间的最佳方法是在与其父元素相同的名称空间中创建新的子元素:
function setupProject($projectFile) {
[xml]$root = Get-Content $projectFile;
$project = $root.Project;
//UPDATE THIS LINE $beforeBuild = $root.CreateElement("Target", "");
$beforeBuild = $root.CreateElement("Target", $project.NamespaceURI);
$beforeBuild.SetAttribute("name", "BeforeBuild");
$beforeBuild.RemoveAttribute("xmlns");
$project.AppendChild($beforeBuild);
$root.Save($projectFile);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21952 次 |
| 最近记录: |