I have an xml file that I am using linq-to-XML to read. Linq-to-XML is preserving the line breaks and spaces for indenting.
So instead of having a guid like this:
"FB5417E2-DB15-481d-80D6-D0C4CB26EB1F"
I am getting stuff like this:
"\n FB5417E2-DB15-481d-80D6-D0C4CB26EB1F"
I have made this method to try and help compensate for this:
public static string ValueTrimmed(this XElement element)
{
if (element != null)
// Remove the newlines and spaces
return element.Value.Replace("\n ", "");
return "";
}
The problem is that this only works for "\n" + 6 spaces.
Is there a way to remove "\n" + Any number of spaces?
No开发者_开发技巧te: I have some scenarios where the "\n" + x spaces is on the inside of the value.
For example:TextTextTextTextTextTextText\n TextTextTextTextTextTextText
Remove all newlines followed by spaces:
return Regex.Replace(element.Value, @"\n\s*", String.Empty);
If you want to preserve a single space between lines:
return Regex.Replace(element.Value, @"\n\s*", " ").Trim();
You could try using string.Trim
to remove all leading and trailing whitespace:
return element.Value.Trim();
Instead of fiddling around with regular expressions, specify whether white-space is preserved or not when you create your XDocument
using the appropriate LoadOptions
:
Preserve white-space:
var xdoc1 = XDocument.Parse("<root>\r\n</root>", LoadOptions.PreserveWhitespace);
var xdoc2 = XDocument.Load(@"\path\to\xml", LoadOptions.PreserveWhitespace);
Ignore white-space:
var xdoc1 = XDocument.Parse("<root>\r\n</root>", LoadOptions.None);
var xdoc2 = XDocument.Load(@"\path\to\xml", LoadOptions.None);
string result = input
.Replace("\\n", String.Empty) // replace escaped \n with nothing
.Trim(); // removing leading (and trailing) spaces
or (try, not sure)
string result = input.Trim(new[] { '\n' });
enter code hereIf were you, inside the outer if place another if checking for "\n" and if that returns true then in a loop check for "\" or "n" or " " and replace with "".
Essentially something like this in pseudo-code...
if (string != null) //check if string is not null
{
if ((string.indexOf(0) == "\\") && (string.indexOf(1) == "n")) //check if string begins with \n
{
for (int i = 0; i < string.length; i++) \\since string begins with "\n" iterate until each character is neither "\", "n", " " and replace each one of those with ""
{
if((string.indexOf(i) == "\\") || (string.indexOf(i) == "n") || (string.indexOf(i) == " "))
string.indexOf(i) = "";
}
}
}
excuse me, that might be a little messy and some of the syntax may be slightly off, but you get the jist.
精彩评论