2016-10-19 5 views
2

次のコードはBuilding Phoneを出力しますが、出力はuxPhoneではありません。
1)Property子孫のコレクションを取得する必要がありますか?
2)これは非常に冗長なようですが、これを行うのに短い形式がありますか?代わりに、単一のいずれかを選択control.Element("Property")Linq to Xmlは最初の子孫値のみを出力しています

var xmlstr = 
     @"<Form> 
     <ControlsLayout> 
     <Object type='sometype' children='Controls'> 
     <Property name='ControlLabel'>BuildingPhone</Property> 
     <Property name='Name'>uxPhone</Property> 
     </Object> 
     </ControlsLayout> 
     </Form>"; 

XElement xelement = XElement.Parse(xmlstr);  
var controls = xelement.Descendants("Object"); 
foreach (var control in controls) 
{ 
    var xElement = control.Element("Property"); 
    if (xElement != null) 
    { 
     var xAttribute = xElement.Attribute("name"); 
     if (xAttribute != null && xAttribute.Value == "ControlLabel") 
      { Console.WriteLine(xElement.Value); } 
      if (xAttribute != null && xAttribute.Value == "Name") 
      { Console.WriteLine(xElement.Value); } 
    } 
} 
+0

MostafizとGiladありがとうございました。私はあなたのうちの1人に答え、もう1人にはアップヴォートをマークします。 Giladさんのコードは、6.0の言語機能のために私のために機能しませんでしたか?もしあなたが6.0の機能を説明するならば、あなたはそれを4.5で再加工することができます。 – bkolluru

答えて

1

ですべてを選択control.Elements("Property")を使うのか?

control.Element("Property")Element関数を使用すると、1つの要素が返されます。代わりにElementsを使用します。

これは非常に冗長なようですが、これを行うのに短い形式がありますか?すべて一緒に

よりよい方法はDescendants("Property")使用することです(あなたのXMLで再帰的に検索し、指定した<>の要素のコレクションを返します)、代わりにif文のwhere句を使用する:

XElement xelement = XElement.Parse(xmlstr); 
var result = from element in xelement.Descendants("Property") 
      let attribute = element.Attribute("name") 
      where (attribute != null && attribute.Value == "ControlLabel")|| 
        (attribute != null && attribute.Value == "Name") 
      select element.Value; 

foreach(var item in result) 
    Console.WriteLine(item); 

// Building Phone 
// uxPhone 
+0

@bkolluru - これはあなたのために機能しましたか? –

+0

GiladさんがOPにコメントしました。 – bkolluru

+0

@bkolluru - 修正を参照してください。ところで、もし両方の答えが役に立つと分かったら、両方をupvoteすることができます。そして、まだそれらの1つを解決したものとしてマークしてください –

3

、私は多分プロパティの子孫のコレクションを取得であるべきProperty

XElement xelement = XElement.Parse(xmlstr); 
//var controls = xelement.Descendants("ControlsLayout"); 
var controls = xelement.Descendants("Object"); 
foreach (var control in controls) 
{ 
    var xElement = control.Elements("Property"); // change this line 
    foreach (var element in xElement) 
    { 
     if (element != null) 
     { 
      var xAttribute = element.Attribute("name"); 
      if (xAttribute != null && xAttribute.Value == "ControlLabel") 
      { Console.WriteLine(element.Value); } 
      if (xAttribute != null && xAttribute.Value == "Name") 
      { Console.WriteLine(element.Value); } 
     } 
    } 

} 
関連する問題