2013-03-02 60 views
2

我知道這可能比我做得更容易。我可以將所有機器從XElement中取出,但我試圖弄清楚如何用特定的序列號拔出機器。在下面的XML片段,我想使用的機器,其中序列= 1通過內部元素查詢特定數據的最佳方式是什麼?

XML:

<Location> 
    <Sequence>1</Sequence> 
    <Machines> 
    <Machine></Machine> 
    <Machine></Machine> 
    </Machines> 
</Location> 
<Location> 
    <Sequence>2</Sequence> 
    <Machines> 
    <Machine></Machine> 
    <Machine></Machine> 
    </Machines> 
</Location> 

代碼:

IEnumerable<XElement> locSeqMachines = 
         from seq in LocationRows.Descendants("Location") 
         select seq; 

var eMachines = locSeqMachines.Descendants("Machine"); 
foreach (var machine in eMachines) 
{ 
} 

回答

2

像這樣的東西應該做的工作:

int soughtId = 1; // Assuming this is coming from somewhere 
string soughtIdStr = soughtId.ToString(); 
var machines = LocationRows.Descendants("Location") 
          .Where(l => (string)l.Element("Sequence") == 
             soughtIdStr) 
          .Descendants("Machine"); 
+0

這就像一個魅力。謝謝大家的回覆。 – Sparhawk 2013-03-02 19:06:25

1

您可以使用XPath通過選擇節點一個特定的順序:

XmlNodeList nodeList = root.SelectNodes("descendant::Location[Sequence='1']"); 
1

此代碼將組中的所有機器數據進行過濾,對位置的序列值的位置標籤:

var locSeqMachines = from seq in LocationRows.Descendants("Location") 
        where seq.Element("Sequence").Value == "1" 
        select new { 
         Sequence = seq.Element("Sequence").Value, 
         Machines = from m in seq.Descendants("Machines").Elements() 
            select m.Value 
        }; 

下面是一些代碼演示瞭如何訪問數據(和測試片段):

foreach (var location in locSeqMachines) { 
    Console.WriteLine("sequence: {0}", location.Sequence); 
    foreach (var machine in location.Machines) { 
     Console.WriteLine(" machine: {0}", machine); 
    } 
} 
0

在解析給定的XML,您可以使用this方法不提高多根元素的錯誤的答案到達。

var xmlText = @"<root> 
         <Location> 
         <Sequence>1</Sequence> 
         <Machines> 
          <Machine></Machine> 
          <Machine></Machine> 
         </Machines> 
         </Location> 
         <Location> 
         <Sequence>2</Sequence> 
         <Machines> 
          <Machine></Machine> 
          <Machine></Machine> 
         </Machines> 
         </Location> 
         </root>"; 

    var elements  = XElement.Parse(xmlText); 
    var machineWith1 = from subElem in elements.Elements("Location") 
          where subElem.Element("Sequence").Value == "1" 
          select subElem.Element("Machines").Elements("Machine"); 

,那麼你可以檢查machineWith1的這個值,

相關問題