2011-02-15 145 views
0

字段中的XML格式如下幫助解析使用LINQ to XML

<ExtraFields> 
     <Field id="Attribute 1" description="Attribute1"> 
      <Value>Value of Attribute 1</Value> 
     <Field id="Attribute 2" description="Attribute2"> 
      <Value>Value of Attribute 2</Value> 
     <Field id="Attribute 3" description="Attribute3"> 
      <Value>Value of Attribute 3</Value> 
</ExtraFields> 

我寫一個LINQ聲明,應返回下列值

Value of Attribute 1 
Value of Attribute 2 
Value of Attribute 3 

返回我的每個值屬性當父節點具有字段id =「屬性X」屬性時description =「AttributeX」

+0

你可以張貼一些示例XML?還問一個問題? – AndrewC 2011-02-15 16:07:51

+0

嗨,Morpheus,我認爲XML的一個樣本會對你確切想要的內容有所幫助和一點澄清。你的問題有點不清楚(至少對我來說)。 – 2011-02-15 16:09:02

+0

對不起,不清楚。到目前爲止,我從未在過去的一年裏在這裏發佈過任何內容。這是我第一次。下次我會堅持正確的標準!感謝您的迴應! – Venki 2011-02-15 19:22:06

回答

4

試試這個

var doc = XElement.Load("test.xml"); 
var results = doc.Descendants("Value").Where(x => 
x.Parent.Attribute("id").Value.StartsWith("Attribute")).Select(x => x.Value); 
2

您發佈的內容是格式不正確的XML,假設您的真實含義如下:

<ExtraFields> 
    <Field id="Attribute 1" description="Attribute1"> 
    <Value>Value of Attribute 1</Value> 
    </Field> 
    <Field id="Attribute 2" description="Attribute2"> 
     <Value>Value of Attribute 2</Value> 
    </Field> 
    <Field id="Attribute 3" description="Attribute3"> 
     <Value>Value of Attribute 3</Value> 
    </Field> 
</ExtraFields> 

在這種情況下,在與LINQ解決您的問題,以XML:

XElement doc = XElement.Load("test.xml"); 
var results = doc.Descendants("Value") 
       .Where (x=> x.Parent.Attribute("id").Value.StartsWith("Attribute") 
           && x.Parent.Attribute("description") != null 
           && x.Parent.Attribute("description").Value.StartsWith("Attribute")) 
       .Select(x => new { Id = x.Parent.Attribute("id").Value, 
            Value = x.Value }); 

foreach(var result in results) 
{ 
    Console.WriteLine(string.Format("{0} : Value = {1}", 
         result.Id, 
         result.Value)); 
}