简体   繁体   English

Powershell从XML删除节点并在保存时删除空行

[英]Powershell remove nodes from XML and remove empty lines when saving

Via an Rest-API call I receive an XML file in Powershell. 通过Rest-API调用,我在Powershell中收到一个XML文件。

#calling the REST service and get XML result
$xml = try {
    Invoke-RestMethod -Uri $url -ErrorAction Stop   
} catch {
    LogWrite "An exception was caught: $($formatstring -f $fields)";
    exit;
}

I then remove nodes by using removeChild() . 然后,我使用removeChild()删除节点。

#manipulate XML
$xml.SelectNodes("//XPathQuery").ParentNode.RemoveChild(...)

Finally I save the manipulated XML. 最后,我保存了操纵的XML。

#save XML
$xml.Save("$targetDirectory\$filename");

The resulting XML-file has multiple empty lines. 生成的XML文件具有多个空行。

在此处输入图片说明

I assume that each removed note resulted in one additional empty line. 我假设每个删除的注释都会导致一个额外的空行。 How can this be avoided? 如何避免这种情况?

The cause of this problem is that the PreserveWhitespace property of XmlDocument is true. 此问题的原因是XmlDocumentPreserveWhitespace属性为true。
The output of Invoke-RestMethod seems to set the PreserveWhitespace property to ture by default. Invoke-RestMethod的输出似乎默认将PreserveWhitespace属性设置为ture。

But setting $doc.PreserveWhitespace = $false to the output of Invoke-RestMethod does not solve the problem because line feed codes remain. 但是将$doc.PreserveWhitespace = $false设置到Invoke-RestMethod的输出并不能解决问题,因为保留了换行代码。

I can not find the option to unset PreserveWhitespace in Invoke-RestMethod , so I think converting the response to XmlDocument by yourself is the easiest solution. 我在Invoke-RestMethod找不到取消PreserveWhitespace设置的选项,因此我认为自己将响应转换为XmlDocument是最简单的解决方案。

$doc = New-Object System.Xml.XmlDocument
$doc.LoadXml((Invoke-WebRequest -Uri $url).Content)

I normally use xml databases to handle small multi attribute databases and had this error I used a linq statement and had to use from, where, and select to select just the elements I wanted to delete. 我通常使用xml数据库来处理小型多属性数据库,并且遇到此错误,我使用了linq语句,并且不得不从from,where和选择仅选择要删除的元素。

var elementsToSelect = from ele in xmlDoc.Elements("List").Elements("Entry")
                       where ele != null && ele.Attribute("Name").Value.Equals(DropDownList1.SelectedValue)
                        select ele;

I would have to see the query to see if you are selecting a board range of nodes or just a single one like I did above that solved my error. 我将不得不查看该查询,以查看您是在选择板级范围的节点还是仅是一个,如我在上面所解决的那样。 I was one level off and it selected all the nodes and removed them. 我是一级用户,它选择了所有节点并将其删除。

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

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