C# Remove newlines from xml loaded -
i have created manually xml file (databasequeries.xml) follows (it contains database queries):
<?xml version="1.0" encoding="utf-8" ?> <queries> <query1> select a, b table1 z = 1 </query1> <query2> select a, b table2 </query2> </queries>
xml file contains newlines , spaces. add xml file resource file in project , load using:
xelement resource = xelement.parse(properties.resources.databasequeries);
i want read query element , convert string do:
resource.element("query1").value
but lot of spaces , newlines (\n). don't worry spaces remove \n or read value xml without containing \n.
i use string request values database later using sqlcommand, etc.
how can this?
you can use regular expression replace newlines , repetitive whitespaces single whitespace:
var query1 = regex.replace(resource.element("query1").value.trim(), @"\s+", " ");
from \s metacharacter - whitespace character can be:
- a space character
- a tab character
- a carriage return character
- a new line character
- a vertical tab character
output:
"select a, b table1 z = 1"
note!: @evk stated, approach simple, can modify string literals used in queries. haven't seen literals contain several whitespaces in row, should aware of behavior. if want sql formatting 100% safe, should parse given sql query syntax tree. , convert syntax tree formatted sql query. can use tools antlr that, or check sql parsing samples.
Comments
Post a Comment