2015-06-21 138 views
-4

我從幾個進程中獲取機器生成的XML。它們的結構如下所示:用C解析XML#

<Data> 
    <Report> 
    <Machine name="hostA"> 
     <MachineInfo location="LA"> 
     <function name="run">Late</function> 
     <function name="status">Complete</function> 
     <function name="date">2015-06-14</function> 
     </MachineInfo> 
     <RepItem name="1488" direction="NS"> 
     <Desc>None Found</Desc> 
     <Status Int="A12">Uplink</Status> 
     </RepItem> 
     <RepItem name="1489" direction="S"> 
     <Desc>31Ghz Ant at 285ft.</Desc> 
     <Status Int="D5">Active</Status> 
     </RepItem> 
     <RepItem name="1438" direction="W"> 
     <Desc>West N. Oc. Backup</Desc> 
     <Status Int="A11">Disabled</Status> 
     </RepItem> 
     <RepItem name="1141" direction="SE"> 
     <Desc>MDT Co.</Desc> 
     <Status Int="B7">Active</Status> 
     </RepItem> 
    </Machine> 
    <Machine name="hostB"> 
     <MachineInfo location="E. LA"> 
     <function name="run">Late</function> 
     <function name="status">Complete</function> 
     <function name="date">2015-06-14</function> 
     </MachineInfo> 
     <RepItem name="1488" direction="NS"> 
     <Desc>None Found</Desc> 
     <Status Int="A12">Down</Status> 
     </RepItem> 
     <RepItem name="1489" direction="S"> 
     <Desc>31Ghz Ant at 285ft.</Desc> 
     <Status Int="D5">Active</Status> 
     </RepItem> 
     <RepItem name="1438" direction="W"> 
     <Desc>West N. Oc. Backup</Desc> 
     <Status Int="A11">Disabled</Status> 
     </RepItem> 
     <RepItem name="1141" direction="SE"> 
     <Desc>MDT Co.</Desc> 
     <Status Int="B7">Active</Status> 
     </RepItem> 
    </Machine> 
    </Report> 
</data> 

所以我用的XDocument和LINQ玩耍了,但我無法弄清楚如何處理重複元素。代碼我扮演的最後一塊看起來有點像這樣:

XDocument report = XDocument.Load(filename); 
foreach (XElement element in report 
    .Element("Machine") 
    .Elements("RepItem")) 
    { 

所有我想做的是吸在XML和解析它,所以我可以將其加載到記錄保存數據庫,並通過存儲報告程序。

+2

您應該反序列化XML而不是手動解析它 – gaiazov

回答

0

在這個例子中,XML被髮送到xmlContent字符串變量,並且數據的根(重複的那個)是Table。 cust_id和cust_name是要在屬性Customer中使用相同名稱的Customer類中讀取的XML標記。

string xmlContent ="the xml content";   

XDocument doc = XDocument.Parse(xml); 

       var data = from item in doc.Descendants("Table") 
          select new Customers 
          { 
           cust_id = XMLManager.TryGetElementValue(item, "cust_id"), 
           cust_name = XMLManager.TryGetElementValue(item, "cust_name"), 

          };