2011-02-16 7 views
9

결국 XML 노드에 저장되는 TextBox가 있습니다. SecurityElement.Escape (string2Escape)을 사용하여 xml을 저장하기 전에 유효하지 않은 문자를 이스케이프 처리합니다.SecurityElement.IsValidText는 "&"...에 대해 true를 반환합니다 ... 이유가 무엇입니까?

문제점 : 이스케이프 메소드를 실행해야하는지 테스트하기 위해 IsValidText를 사용했지만 실제로는 '' '와'& '을 반환하지만 유효한 경우 xml 시스템 barfs를 저장하면 사실 , 유효하지. '<'또는 '>'에만 false를 반환하는 것으로 보입니다.

간단한 해결책, 수표를 제거하십시오,하지만 제 질문은 왜 이런 경우입니까?

private string EscapeXML(string nodeText) 
{ 
    if (!SecurityElement.IsValidText(nodeText)) 
    { 
     return SecurityElement.Escape(nodeText); 
    } 
    return nodeText; 
} 

답변

2

SecurityElement 생성자가 이미 자체적으로 "&"문자를 포함하여 이스케이프 처리를 수행하고 있으므로 IsValidText는 생성자가 이미 처리하지 않은 문자 만 확인하는 것처럼 보입니다. 따라서 SecurityElement를 사용하여 전체 XML을 작성하지 않는 한 SecurityElement의 IsValidText/Escape 콤보를 사용하는 것이 안전하지 않습니다.

내가 예를 더 잘 설명하려고합니다

:

using System; 
using System.Diagnostics; 
using System.Security; 

class MainClass 
{ 
    public static void Main (string[] args) 
    { 
     // the SecurityElement constructor escapes the & all by itself 
     var xmlRoot = 
      new SecurityElement("test","test &"); 

     // the & is escaped without SecurityElement.Escape 
     Console.WriteLine (xmlRoot.ToString()); 

     // this would throw an exception (the SecurityElement constructor 
     // apparently can't escape <or>'s 
     // var xmlRoot2 = 
     // new SecurityElement("test",@"test & > """); 

     // so this text needs to be escaped before construction 
     var xmlRoot3 = 
      new SecurityElement("test",EscapeXML(@"test & > """)); 
     Console.WriteLine (xmlRoot3.ToString()); 

    } 

    private static string EscapeXML(string nodeText) 
    { 
     return (SecurityElement.IsValidText(nodeText))? 
      nodeText : 
      SecurityElement.Escape(nodeText); 
    } 
} 
5

가 여기에 내가 리플렉터에서 가져온 내용은 ​​다음과 같습니다

내 실패 코드는 다음과 같습니다. enter image description here enter image description here

이렇게하면 동작 방식이 어떻게되는지 설명 할 수 있습니다. 당신이 찾고있는 것을 수행하는 SecurityElement에 어떤 메소드도 보이지 않지만, 확장 메소드로서 아마도 당신 자신을 구현하기에 충분히 간단합니다.

관련 문제