venky
venky

Reputation: 53

Trim White Spaces from all XML Values

Can anyone please help me on how to remove all the white spaces from XML values as shown below:

<organization>
  <Department>
    <Name>IT</Name>
    <Location> Australia </Location>
  </Department>
</organization>

To:

<organization>
  <Department>
    <Name>IT</Name>
    <Location>Australia</Location>
  </Department>
</organization>

Upvotes: 1

Views: 2266

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18155

Believe you want to trim the whitespaces in values. In this scenario, you could select all the leaf nodes using Linq to Xml and use String.Trim() to delete all leading and trailing whitespaces

var xDoc = XDocument.Parse(xml);
var nodes = xDoc.Descendants().Where(x=>!x.Elements().Any()); // Select all leaf nodes
foreach(var node in nodes)
{
    node.Value = node.Value.Trim(); // Remove leading and trailing whitespaces
}

var result = xDoc.ToString();

Demo Code

Upvotes: 3

Related Questions