2010-03-23 4 views
3

우리 app에서는 objectName, propertyValue, propertyType의 형식으로 개체 유형에 관계없이 동일한 데이터베이스 테이블에 개체의 속성을 저장해야합니다. 우리는 XamlWriter를 사용하여 주어진 객체의 모든 속성을 저장하기로 결정했습니다. 그런 다음 XamlReader를 사용하여 만든 XAML을로드하고 속성 값으로 되돌립니다. 이것은 빈 문자열을 제외하고는 대부분 잘 동작합니다. XamlWriter는 아래와 같이 빈 문자열을 저장합니다.XamlReader.Parse가 빈 문자열에서 예외를 throw합니다.

<String xmlns="clr-namespace:System;assembly=mscorlib" xml:space="preserve" /> 

은 XamlReader이 문자열을보고 문자열을 만들려고하지만, 사용하는 String 객체에 빈 생성자를 찾을 수없는, 그래서 그것은의 ParserException가 발생합니다.

내가 생각할 수있는 유일한 해결 방법은 빈 문자열 인 경우 실제로 속성을 저장하지 않는 것입니다. 그런 다음 속성을로드 할 때 어떤 항목이 존재하지 않는지 확인할 수 있습니다. 즉 빈 문자열 일 것입니다.

해결 방법이 있습니까? 아니면 더 좋은 방법이 있습니까?

답변

0

문자열을 serialize 할 때 이와 비슷한 문제가있었습니다. 우리가 해결할 수있는 유일한 방법은 StringWrapper 구조체 또는 적절한 생성자가있는 클래스를 만드는 것입니다. 그런 다음이 유형을 사용하여 문자열 값을로드하고 저장했습니다.

0

또한 문제가 발생하여 웹에서 솔루션을 검색했지만 찾을 수 없습니다.

static string FixSavedXaml(string xaml) 
    { 
     bool isFixed = false; 
     var xmlDocument = new System.Xml.XmlDocument(); 
     xmlDocument.LoadXml(xaml); 
     FixSavedXmlElement(xmlDocument.DocumentElement, ref isFixed); 
     if (isFixed) // Only bothering with generating new xml if something was fixed 
     { 
      StringBuilder xmlStringBuilder = new StringBuilder(); 
      var settings = new System.Xml.XmlWriterSettings(); 
      settings.Indent = false; 
      settings.OmitXmlDeclaration = true; 

      using (var xmlWriter = System.Xml.XmlWriter.Create(xmlStringBuilder, settings)) 
      { 
       xmlDocument.Save(xmlWriter); 
      } 

      return xmlStringBuilder.ToString(); 
     } 

     return xaml; 
    } 

    static void FixSavedXmlElement(System.Xml.XmlElement xmlElement, ref bool isFixed) 
    { 
     // Empty strings are written as self-closed element by XamlWriter, 
     // and the XamlReader can not handle this because it can not find an empty constructor and throws an exception. 
     // To fix this we change it to use start and end tag instead (by setting IsEmpty to false on the XmlElement). 
     if (xmlElement.LocalName == "String" && 
      xmlElement.NamespaceURI == "clr-namespace:System;assembly=mscorlib") 
     { 
      xmlElement.IsEmpty = false; 
      isFixed = true; 
     } 

     foreach (var childElement in xmlElement.ChildNodes.OfType<System.Xml.XmlElement>()) 
     { 
      FixSavedXmlElement(childElement, ref isFixed); 
     } 
    } 
:

난 (XamlWriter로부터 출력 FixSavedXaml 공급)를 다음과 같이 빈 문자열을 저장 한 XML 검사 고정하여 해결

관련 문제