开发者

Linq to XML, C# and Encoded Characters in XML

I have a string in XML that looks like this:

I am a sample strin开发者_如何转开发g & I have an ampersand.

When I display this to the use it looks like this:

I am a sample string & I have an ampersand.

The user can interact with this string and when they are done, their changes are stored in the database only the indices are off because the string they interacted with is shorter than the one in the XML.

For example: If a user puts a line break at the end of the string like this:

I am a sample string & I have an

ampersand

The database will store it and the new XML created from it will look like this (off by 4):

I am a sample string & I have

an ampersand

Is it best to just handle this in code and make the adjustment before I put it in the database? Seems like this would be less desirable because I'd have to handle this for all encoded characters and who knows how many there are and I'd have to do it for all languages.

Is there is something in Linq to XML that handles this situation?

Advice?

Thank you,

Aaron


You shouldn't have to handle this - LINQ to XML will take care of forming valid XML in this case:

XElement ele = new XElement("foo");
ele.Value = "I am a sample string & I have an ampersand.";
string text = ele.ToString();//<foo>I am a sample string &amp; I have an ampersand.</foo>
string value = ele.Value; //I am a sample string & I have an ampersand.

ele.Value = "I am a sample string &amp; I have an ampersand.";
string text = ele.ToString();//<foo>I am a sample string &amp;amp; I have an ampersand.</foo>
string value = ele.Value; //I am a sample string &amp; I have an ampersand.

You should be worried about storing valid values in your database, not the representation of those values (be it XML or otherwise).


Your index on the second string is off by four probably because you aren't counting the removal of the 4 chars "amp;"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜