2016-07-30 70 views
0
List<string> list = new List<string>(); 
foreach (XPathNavigator node in nav.Select("configuration/company/work/worktime")) 
      { 
       string day = getAttribute(node, "day"); 
       string time = getAttribute(node, "time"); 
       string worktype = ?? // how to get worktype attribute valuefrom parent node 
       list.Add(day,time,worktype); // add to list 
      } 

</configuration> 
     <company> 
     <work worktype="homeWork"> 
      <worktime day="30" time="10:28"></worktime> 
      <worktime day="25" time="10:50"></worktime> 
     </work> 
     <work worktype="officeWork"> 
      <worktime day="12" time="09:28"></worktime> 
      <worktime day="15" time="12:28"></worktime> 
     </work> 
     </company> 
    </configuration> 


need output as : 
list[0] = homeWork,30,10:28 
list[1] = homeWork,25,10:50 
list[2] = officeWork,12,09:28 
list[3] = officeWork,15,12:28 

我想從XML名單,但未能像上面給出的(使用XPath導航器獲取輸出,我怎麼能訪問父節點得到worktype屬性從XML獲取列表,以及其他剩餘內部節點屬性?無法使用的XPathNavigator

回答

0

我建議使用LINQ to XML了XPath的,但如果你必須使用XPathNavigator那麼你需要遍歷每個work元素,然後它的每一個worktime子元素。這樣,您就可以從父上下文中使用worktype

foreach (XPathNavigator work in nav.Select("configuration/company/work")) 
{ 
    var workType = work.GetAttribute("worktype", string.Empty); 

    foreach (XPathNavigator worktime in work.Select("worktime")) 
    { 
     var day = worktime.GetAttribute("day", string.Empty); 
     var time = worktime.GetAttribute("time", string.Empty); 

     list.Add($"{workType}, {day}, {time}"); 
    } 
} 

了工作演示見this fiddle

+0

很酷的工作,你能解釋一下爲什麼「string.Empty」已被採用 –

+0

XML中的名字是由兩部分:命名空間和本地名稱。此處使用'string.Empty'或'「」'是因爲XML中的名稱沒有名稱空間。 –

0

使用嵌套循環。最初configuration/company/work檢索工作節點,檢索一個變量worktype屬性和存儲。然後,通過孩子worktype節點環和一個字符串添加到列表中的每一個

+0

嘗試相同,但是當我做配置/公司/工作/工作時間foreach它爲相同的工作類型添加了雙項,意味着以上是homeWork 2記錄 - 我得到4記錄它包括其2自己和另一個2記錄officeWork –

+0

可以共享相同的代碼 –

0

使用Net Library增強版xml(linq xml)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILENAME); 
      var results = doc.Descendants("work").Select(x => new { 
       worktype = (string)x.Attribute("worktype"), 
       worktime = x.Elements("worktime").Select(y => new { 
        day = (int)y.Attribute("day"), 
        time = (DateTime)y.Attribute("time") 
       }).ToList() 
      }).ToList(); 
     } 
    } 
} 
+0

感謝它的工作,但我必須做到這一點與xPathNavigator –

+0

我不喜歡使用第三方DLL可以包含病毒。 – jdweng

+1

@jdweng是啊,那個來自微軟的'System.Xml.dll'通常會帶有病毒;) –