2014-10-29 68 views
-1

我有XDocument.Load()從文件 加載xml和XDocument.parse()從字符串加載xml, 可以找到任何方式來組合和從文件或字符串動態加載?可以將XDocument.Load()和XDocument.parse()組合成一個嗎?

+0

請重新表述您的問題。不清楚你想要什麼 – Jehof 2014-10-29 09:20:15

+0

那麼,你可以編寫代碼來選擇使用哪種方法,這取決於XML來自哪裏。如果你問是否有一個框架方法在運行時根據類型調用'Load'或'Parse',那麼不,沒有。 – Tim 2014-10-29 09:23:02

+0

@Jehof - 我不認爲'linq-to-xml'標籤在這裏一定是適用的,因爲這個問題對於LINQ沒有任何問題,即使'XDocument'是linq-到XML。 – Tim 2014-10-29 09:25:51

回答

0

根據你的意思是XDocument.PARSE()而不是XDocument.PRASE()的假設,我相信下面的函數應該在這方面幫助你。 我們只是在加載它之前檢查文件是否存在,如果它不存在,那麼它應該是一個xml字符串。在這兩種情況下,我們用try catch覆蓋自己並返回null。

要使用下面的內容,我會在繼續之前仔細檢查返回值是否爲空。

if(LoadXml(xmlFile) == null) 
{ 
    //enter code for fail to load, will continue if correct. 
} 

的功能:

 private XDocument LoadXml(string xmlFile) 
    { 
     //initialise a new XDocument 
     XDocument doc = new XDocument(); 

     //check to see if xmlFile exists as a file in the OS. 
     if (File.Exists(xmlFile)) 
     { 
      //try XDocument.load() 
      try 
      { 
       doc = XDocument.Load(xmlFile); 
      } 
      catch (Exception) 
      { 
       //if the load did not succeed then return null 
       return null; 
      } 
     } 
     else 
     { 
      //if it is not a file then try parsing the string. 
      try 
      { 
       doc = XDocument.Parse(xmlFile); 
      } 
      catch (Exception) 
      { 
       //if the parse failed (i.e. the string is not an xml format) then make doc = null 
       return null; 
      } 
     } 
     //return doc 
     return doc; 
    } 
+1

爲什麼使用'Stream'來加載'XDocument'?如果文件存在,只需使用'XDocument.Load(string)'重載。 – Tim 2014-10-29 09:27:25

+0

一個非常好的點蒂姆。在這種情況下,我們不需要其他任何xmlFile。我現在要修改它 – 2014-11-04 10:41:31

相關問題