2010-11-18 94 views
1

我正在構建Silverlight 4應用程序。我試圖使用XElement來讀取XML。下面的代碼不爲我工作:Silverlight:錯誤反序列化XML

 string data = @"<?xml version='1.0'> 
         <Data> 
          <TopicGroups> 
          <TopicGroup> 
           <Name>Documents</Name> 
           <Id>0</Id> 
          </TopicGroup> 
          </TopicGroups> 
          <Topics> 
          <Topic> 
           <Name>Foo stuff</Name> 
           <Id>1</Id> 
           <GroupId>0</GroupId> 
          </Topic> 
          </Topics> 
          <PlumFiles> 
          <PlumFile> 
           <Name>moons</Name> 
           <Body>we're going to the moon</Body> 
           <TypeExtension>docx</TypeExtension> 
           <Author>Frodo</Author> 
           <CreatedOn>2010-11-18T00:00:00-05:00</CreatedOn> 
          </PlumFile> 
          </PlumFiles> 
         </Data>"; 

     // crash here 
     XElement xml = new XElement(data); 

唯一的例外是:

System.Xml.XmlException: Name cannot begin with the '<' character, hexadecimal value 0x3C. 

    at System.Xml.XmlConvert.VerifyNCName(String name, ExceptionType exceptionType) 
    at System.Xml.XmlConvert.VerifyNCName(String name) 
    at System.Xml.Linq.XName..ctor(XNamespace ns, String localName) 
    at System.Xml.Linq.XNamespace.GetName(String localName, Int32 index, Int32 count) 
    at System.Xml.Linq.XNamespace.GetName(String localName) 
    at System.Xml.Linq.XName.Get(String expandedName) 
    at System.Xml.Linq.XName.op_Implicit(String expandedName) 
    at PlumPudding.MainPage.MainPage_Loaded(Object sender, RoutedEventArgs e) 
    at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) 
    at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)} System.Exception {System.Xml.XmlException} 

我應該怎麼做是錯在這裏幹什麼?

回答

1

您應該使用: -

XElement xml = XElement.Parse(data); 

的構造函數的XElement期待的XName定義元素的簡單的名稱來構造(或將要implictly轉換爲XName字符串)。

+0

很好,謝謝 – 2010-11-18 17:56:13