XElement.SetText encoding issue with single and double quotes

  • Thread starter Thread starter 1
  • Start date Start date

1

New Member
I have a very specific problem with the XElement class in regards to an applciation I am working on. Say I try setting the element value to "test & testing more < >"\[code\] XElement tester = updatedElement.XPathSelectElement("Test"); tester.SetValue("test & testing more < >"); // outputs //<Test>test & testing more < ></Test>\[/code\]That is correct and fine, but because of the limitations of the application I am working with I need to also encode single and double quotes. Say I clean up the input before I call XElement.SetText() by calling.\[code\] XElement.SetText(stringValue.EscapeXml()) public static string EscapeXml(this string s) { string xml = s; if (!string.IsNullOrEmpty(xml)) { xml = xml.Replace("\"", """); xml = xml.Replace("'", "&apos;"); } return xml; }\[/code\]The \[code\]"\[/code\] will turn into \[code\]&quot;\[/code\] when the SetText function is called. So when the HTML is rendered it looks like ", when I really want " to be displayed.The reason why I need single quotes encoded is because there is a service that creates xpath expressions on the run.I.E. - the xpath created by the service will equate to\[code\]XElemenet test = testParent.XPathSelectElement("Test[.='some value with single quote's ']")\[/code\]The single quote will cause an exception when put in as a filter as an xpath expression. You may say, "why can't I just replace the single quote with \[code\]&apos;\[/code\] when the filter is built."The reason I can't is because there are some ID elements that are matched based on the filter having the same value as the XML node. The filter also wouldn't return the element, as the parent did not have anything matching the filtered expression.The double quotes come into play because I am passing a huge chunk of XML to a service, and the service converts the XML I passed in to another form of XML. Then the service sends the XML to another service that returns another form with many attributes:so say I sent in the following:\[code\]<test>Some value from the original XML "123"<test/> // cannot encode here, must be done before hand\[/code\]I get back \[code\]<test value="http://stackoverflow.com/questions/10342252/Some value from the original XML"123""/>\[/code\]passing in a double quote to that would result in failure, when evaluating the response. I cannot simply encode it before it goes to the service because the value in the attribute must match exactly with my original element. Does anyone have an extension method for the XElement class that will encode " and ' quotes. I have tried to override SetText, but it isn't working out. Any help on solving this problem would be much appreciated.Thanks!
 
Back
Top