Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to trim the space in the xml string excluding the xml namespace header in c#. My xml string is as below. I want to trim the xml node values alone excluding the namespace header (getInstallmentHistoryReply xmlns:NS1="urn:esbbank.com/gbo/xml/schemas/v1_0/")

XML
<getInstallmentHistoryReply xmlns:NS1="urn:esbbank.com/gbo/xml/schemas/v1_0/">
	<eAI_HEADER>
		<serviceName>GET.FINANCE.DETAIL</serviceName>
		<serviceType>SYNC</serviceType>
		<serviceVersion>1.0</serviceVersion>
		<client>ADIB</client>
		<clientChannel>DDS</clientChannel>
		<msgChannel>HTTP</msgChannel>
		<requestorLanguage>E</requestorLanguage>
		<securityInfo>
			<authentication>
				<UserId>DDS</UserId>
				<Password>XXXXXXXXXX</Password>
			</authentication>
		</securityInfo>
		<returnCode>0000</returnCode>
	</eAI_HEADER>
</getInstallmentHistoryReply>


What I have tried:

My code is as below
string ResponseXML_Updated = ResponseXML.Replace("NS1:getInstallmentHistoryReply", "getInstallmentHistoryReply");
            
            string ResponseXML_Trimmed = System.Text.RegularExpressions.Regex.Replace(ResponseXML_Updated, @"(([^\s]+)\s+)", "$2"); 
           
            
            System.Xml.XmlDocument xd1 = new System.Xml.XmlDocument();
            xd1.LoadXml(ResponseXML_Trimmed);
Posted
Updated 13-Mar-24 6:51am
v4
Comments
Richard Deeming 18-Mar-24 9:25am    
Why? The XmlDocument doesn't care about whitespace between nodes. And if you want to trim space from node values, then it would be far better to load the XML and then process the node values using the XmlDocument.

Trying to use regular expressions to manipulate XML is only going to cause headaches!

1 solution

Two things - firstly, you need to remove the <pre> from your xml or it will not process before you even start to "trim" it.

Secondly you cannot blindly remove all spaces: if you look at the string you generated:
XML
<getInstallmentHistoryReplyxmlns:NS1="urn:esbbank.com/gbo/xml/schemas/v1_0/"><eAI_HEADER><serviceName>GET.FINANCE.DETAIL</serviceName>...
you can see that it is not valid XML: it needs a space between the getInstallmentHistoryReply tag and the xmlns: attribute or the whole looks like a longer attribute name with no proper tag preceding it.
I would suggest that you change your regex to only remove whitespace following a > tag ending marker
 
Share this answer
 
v2
Comments
Maciej Los 13-Mar-24 15:19pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900