Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

c# - How to encode the ampersand if it is not already encoded?

I need a c# method to encode ampersands if they are not already encoded or part of another encoded epxression

eg

"tom & jill" should become "tom & jill"


"tom & jill" should remain "tom & jill"


"tom € jill" should remain "tom € jill"


"tom <&> jill" should become "tom <&amp;> jill"


"tom &quot;&&quot; jill" should become "tom &quot;&amp;&quot; jill"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you actually want to do, is first decode the string and then encode it again. Don't bother trying to patch an encoded string.

Any encoding is only worth its salt if it can be decoded easily, so reuse that logic to make your life easier. And your software less bug-prone.

Now, if you are unsure of whether the string is encoded or not - the problem will most certainly not be the string itself, but the ecosystem that produced the string. Where did you get it from? Who did it pass through before it got to you? Do you trust it?

If you really have to resort to creating a magic-fix-weird-data function, then consider building a table of "encodings" and their corresponding characters:

&amp; -> &
&euro; -> €
&lt; -> <
// etc.

Then, first decode all encountered encodings according to the table and later reencode the whole string. Sure, you might get more efficient methods when fumbling without decoding first. But you won't be sane next year. And this is your carrier, right? You need to stay right in the head! You'll loose your mind if you try to be too clever. And you'll lose your job when you go mad. Sad things happen to people who let maintaining their hacks destroy their minds...

EDIT: Using the .NET library, of course, will save you from madness:

I just tested it, and it seems to have no problems with decoding strings with just ampersands in them. So, go ahead:

string magic(string encodedOrNot)
{
    var decoded = HttpUtility.HtmlDecode(encodedOrNot);
    return HttpUtility.HtmlEncode(decoded);
}

EDIT#2: It turns out, that the decoder HttpUtility.HtmlDecode will work for your purpose, but the encoder will not, since you don't want angle brackets (<, >) to be encoded. But writing an encoder is really easy:

define encoder(string decoded):
    result is a string-builder
    for character in decoded:
        if character in encoding-table:
           result.append(encoding-table[character])
        else:
           result.append(character)
    return result as string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...