Writing XML Exactly as XML Literals are Written
I'm transforming some XML from DrawingML to XAML. Unfortunately, the XAML one is not working as expected with white spaces, but I have found a work around. Here's the problem:
Problem Statment
I want to write the following in a TextBlock:
Hi John, what did Sushi A say to Sushi B?
So I would write:
<TextBlock>
<Run>Hey</Run>
<Run FontWeight="Bold">John</Run>
<Run>,</Run>
<Run FontStyle="Italic">what did Sushi A say to Sushi B?</Run>
</TextBlock>
This doesn't produce the desired results. Instead, it produces:
Hi John , what did Sushi A say to Sushi B?
Notice the space now between "John
" and ",
"? Weird, eh? This is because XAML appends a space between runs. I don't know why it does this. I really do need the formatting exactly as above, so the option of changing formatting, like making the comma bold too is not an option.
Partial Solution
The weirder thing is that there is a way around this - i.e. to lose the extra space that XAML adds - you have to put your runs on the same line. I have no idea why, but that's the case. So the following actually works just fine:
<TextBlock>
<Run>Hey</Run>
<Run FontWeight="Bold">John</Run><Run>,</Run>
<Run FontStyle="Italic">what did Sushi A say to Sushi B?</Run>
</TextBlock>
Notice runs #2 and #3 (of 4 runs) are now on the same line.
Question
The issue I'm having is that I haven't found a way to write the above using XML Literals. If I try this:
Dim tb = <TextBlock>
<Run>Hey</Run>
<Run FontWeight="Bold">John</Run><Run>,</Run>
<Run FontStyle="Italic">what did Sushi A say to Sushi B?</Run>
</TextBlock>
it is always created as the below, with the 4 runs on seperate lines:
<TextBlock>
<Run>Hey</Run>
<Run FontWeight="Bold">John</Run>
<Run>,</Run>
<Run FontStyle="Italic">what did Sushi A say to Sushi B?</Run>
</TextBlock>
Does anyone know how XML can be written exactly as written in XML Literals?
Bonus
If you answer the question correctly, I'll tell you the punchline of the joke :)
I don't suppose using a span will help you (as it will keep non-formatted text out of XML elements so it might not get auto-formatted).
i.e.
<TextBlock>
<Span>
Hey
<Bold>John</Bold>,
<Italic>what did Sushi A say to Sushi B?</Italic>
</Span>
</TextBlock>
Obviously this only fixes the specific case not the general, I would probably suggest not using XML literals :)
Any chance the unicode backspace character would solve your problem?
http://www.fileformat.info/info/unicode/char/0008/index.htm
Update
One other idea. Have you looked into the XDocument.Save(TextWriter textWriter, SaveOptions saveOptions)
method? The documentation says that if you use SaveOptions.DisableFormatting
, it will preserve spacing.
精彩评论