0

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.

enter image description here

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

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.