2010-12-27 12 views
1

私はこのようなフォーマットさオブジェクトのXElementている:私はすべてのノードですべての属性の値を取得する必要がありますが、私は方法がわからないネストされたXMLノードから属性値を取得する方法は?

<Setting guid="3bcedf55-b75f-456b-b90a-a92cbbb022ga"> 
    <PatientFieldList> 
     <PatientFieldSetting PatientName="UserDecision" PatentFieldLength="64" /> 
     <PatientFieldSetting PatientName="prohibited" PatentFieldLength="128" /> 
    </PatientFieldList> 
</Setting> 

を:私は多くを持って

xml.Elements("PatientFieldList") 

xml.Descendants("PatientsSettingsFieldsList").Where(x => x.Attribute("PatentFieldLength").Value == 64)` 

を試してみました/そのようなノードのように私は '[]]または何とかこれらの属性にアクセスする簡単な方法があるのだろうかと思います。これは、XMLの属性を持っているすべてのノードの属性を出力します

答えて

3

コード:

using System; 
using System.Linq; 
using System.Xml.Linq 

var xml = "<Setting ..."; 
var doc = XElement.Parse(xml); 
int i; // for int parse 
var q = from node in doc.Descendants("PatientFieldSetting") 
     let name = node.Attribute("PatientName") 
     let length = node.Attribute("PatentFieldLength") 
     select new { Name = (name != null) ? name.Value : "", Length = (length != null && Int32.TryParse(length.Value, out i)) ? i : 0 }; 

foreach (var node in q) 
{ 
    Console.WriteLine("Name={0}, Length={1}", node.Name, node.Length); 
} 

出力:

Name=UserDecision, Length=64 
Name=prohibited, Length=128 
+0

@PiterK:喜んで助けました! :) – abatishchev

1

XDocument doc = //your data 

var q = from node in doc.Descendants() 
     where node.Attributes().Count() > 0 
     select new {NodeName = node.Name, Attributes = node.Attributes()}; 

foreach (var node in q) 
{ 
    Console.WriteLine(node.NodeName); 
    foreach (var attribute in node.Attributes) 
    { 
     Console.WriteLine(attribute.Name + ":" + attribute.Value); 
    } 
    Console.WriteLine(); 
} 

だけPatientFieldSettingは、名前のフィルタをノードたい場合:

from node in doc.Descendants("PatientFieldSetting") 
関連する問題