2013-01-21 54 views
0

我想從使用XDocument和XElement的XML文檔中獲取值。我試圖獲得三個值,但是當我嘗試返回它們時,它們合併爲一個值。這裏是我搜索XML:如何使用XDocument和XElement將XML作爲單獨的值返回

<create_maint_traveler>  
<Paths> 
     <outputPath value="D:\Intercim\DNC_Share\itcm\DataInput\MCDHeaderDrop\" /> 
     <outputPath_today value="D:\Intercim\DNC_Share\itcm\DataInput\Today\" /> 
     <log value="D:\Intercim\DNC_Share\itcm\Log\CreateMaintLog.log" /> 
    </Paths> 
</create_maint_traveler> 

這裏是我正在查詢值:

XDocument config = XDocument.Load(XML); 
      foreach (XElement node in config.Root.Elements("Paths")) 
      { 
       if (node.Name == "outputPath") outputPath = node.Value; 
       if (node.Name == "outputPath_today") outputPath = node.Value; 
       if (node.Name == "log") outputPath = node.Value; 
      } 

當我輸出到文件中,我發現返回的值是

D:\Intercim\DNC_Share\itcm\DataInput\MCDHeaderDrop\D:\Intercim\DNC_Share\itcm\DataInput\Today\D:\Intercim\DNC_Share\itcm\Log\CreateMaintLog.log 

或者沒有任何回報。我在標籤之外的XML文件中的值返回了一個long值。我很困惑如何分別返回outputPath,outputPath_today和日誌值。任何幫助表示讚賞。

+0

你還沒有顯示你要回來的東西。 (目前還不清楚爲什麼你不只是要求這些值。) –

回答

1

嘗試:

var xDoc = XDocument.Load(XML); 
var paths = xDoc.Root.Elements("Paths"); 

var res = from p in paths 
      select new 
        { 
         outputPath = p.Element("outputPath").Attribute("value").Value, 
         outputPath_today = p.Element("outputPath_today").Attribute("value").Value, 
         log = p.Element("log").Attribute("value").Value 
        }; 

foreach(path in res) 
{ 
     System.Console.WriteLine(path.outputPath); 
     System.Console.WriteLine(path.outputPath_today); 
     System.Console.WriteLine(path.log); 
     // or do anything you want to do with those properties 
} 

您將獲得outputPathoutputPath_todaylog值到匿名對象的IEnumerable。這些對象每個都將具有從XML填充值的屬性outputPath,outputPath_todaylog

相關問題