Powershell remove nodes from XML and remove empty lines when saving

时光怂恿深爱的人放手 提交于 2019-12-11 17:57:43

问题


Via an Rest-API call I receive an XML file in Powershell.

#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().

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

Finally I save the manipulated XML.

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

The resulting XML-file has multiple empty lines.

I assume that each removed note resulted in one additional empty line. How can this be avoided?


回答1:


The cause of this problem is that the PreserveWhitespace property of XmlDocument is true.
The output of Invoke-RestMethod seems to set the PreserveWhitespace property to ture by default.

But setting $doc.PreserveWhitespace = $false to the output of Invoke-RestMethod does not solve the problem because line feed codes remain.

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.

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



回答2:


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.

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.



来源:https://stackoverflow.com/questions/55402196/powershell-remove-nodes-from-xml-and-remove-empty-lines-when-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!