2013-02-20 54 views
4

所以基本上,我在閱讀兩個XML文檔。第一個有兩個需要存儲的值:Name和Value。第二個有四個值:Name,DefaultValue,Type和Limit。在閱讀文檔時,我想將每個存儲到某個對象中。我需要能夠將兩個對象組合成一個有5個值的對象。 XML文檔的長度不同,但第二個文檔的大小始終最小。我應該如何組織兩個對象以便能夠將它們連接到一個鍵上?

例:

<XML1> 
    <Item1> 
    <Name>Cust_No</Name> 
    <Value>10001</Value> 
    </Item1> 
    <Item4> 
    ITEM4 NAME AND VALUE 
    </Item4> 
    <Item7> 
    ITEM 7 NAME AND VALUE 
    </Item7> 
</XML1> 

<XML2> 
    <Item1> 
    <Name>Cust_No</Name> 
    <DefaultValue></DefaultValue> 
    <Type>varchar</Type> 
    <Limit>15</Limit> 
    </Item1> 
    6 MORE TIMES ITEMS 2-7 
</XML2> 

我已經有代碼通過XML循環。我真的只需要考慮什麼是存儲數據的最佳方式。最終,我想能夠加入Name Key上的兩個對象。我嘗試了string[]arrayList[],但我遇到了困難。我也讀了Dictionary,但也遇到了麻煩(我以前從未使用過Dictionary)。

回答

2

這裏是Linq to Xml查詢,它將連接兩個XDocuments併爲聯接項目選擇匿名對象。每個對象有五個屬性:像這樣創建

var query = 
    from i1 in xdoc1.Root.Elements() 
    join i2 in xdoc2.Root.Elements() 
     on (string)i1.Element("Name") equals (string)i2.Element("Name") into g 
    let j = g.SingleOrDefault() // get joined element from second file, if any 
    select new { 
     Name = g.Key, 
     Value = (int)i1.Element("Value"), 
     DefaultValue = (j == null) ? null : (string)j.Element("DefaultValue"), 
     Type = (j == null) ? null : (string)j.Element("Type"), 
     Limit = (j == null) ? null : (string)j.Element("Limit") 
    }; 

XDocuments:

var xdoc1 = XDocument.Load(path_to_xml1); 
var xdoc2 = XDocument.Load(path_to_xml2); 

使用查詢:

foreach(var item in query) 
{ 
    // use string item.Name 
    // integer item.Value 
    // string item.DefaultValue 
    // string item.Type 
    // string item.Limit 
} 
+1

謝謝!這很棒。但是,我現在如何訪問數據?它存儲在什麼地方? – 2013-02-20 17:56:07

+0

@IanBest堅持下去,我會更新樣本 – 2013-02-20 17:56:43

相關問題