2016-10-19 6 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에게 감사드립니다. 나는 너희 중 한 명과 다른 한 명을 업보트로 표시 할 것이다. Gilad 6.0 언어 기능 때문에 코드가 작동하지 않습니까? 당신이 6.0의 특징을 설명하면 보너스가 될 것입니다. – bkolluru

답변

1

모든를 선택 control.Elements("Property")를 사용할 수 있습니까?

control.Element("Property")에서 Element 함수의 사용은 하나의 요소를 리턴한다. 대신 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 - 수정 사항을 참조하십시오. BTW - 두 대답을 모두 찾으면 도움을받을 수 있습니다. 그런 다음 여전히 그 중 하나를 해결 한 것으로 표시하십시오 –

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); } 
     } 
    } 

}