2016-06-27 2 views
0

내 XML 파일의 모양은 다음과 같습니다.XDocument를 반복하고 자식 노드 값을 가져옴

<PictureBoxes> 
    <P14040105> 
    <SizeWidth>100</SizeWidth> 
    <SizeHeight>114</SizeHeight> 
    <locationX>235</locationX> 
    <locationY>141</locationY> 
    </P14040105> 
    <P13100105> 
    <SizeWidth>100</SizeWidth> 
    <SizeHeight>114</SizeHeight> 
    <locationX>580</locationX> 
    <locationY>274</locationY> 
    </P13100105> 
</PictureBoxes> 

실제로 수행하려는 작업은 양식의 각 컨트롤을 반복하고 크기 및 위치 속성을 XML 파일에 저장하는 것입니다. <P...> 노드는 실제로 내 picturebox의 이름이므로이 이름을 사용해야합니다.

XML을 만든 후에 XML 파일을 사용하여 양식의 그림 상자를 다시 만들어 봅니다. 그래서 내가 원하는 것은 <P...> 노드의 이름과 자식 노드의 값을 얻는 것입니다.

+0

@PhilipKendall 음, 아무것도, 처음으로 시도하는 XML과 제가 검색을 발견하는 것은 내가 일의 이름을 알고있을 때이 될 것 같다 e 부모 노드,이 경우에는 그렇지 않습니다. ''과''아래에 값을 가져와야하지만 그 노드 이름을 모르겠습니다. – crimson589

답변

1

xml 파일에서 데이터를로드하고 각각 저장하려면 FormLoadFormClosing 메서드를 확인해야합니다. 각 요소에 대한 PictureBox를 생성하고 XML 데이터의 값을의 설정 PictureBoxes 요소의 자식 요소를 통해 FormLoad 방법 루프에서

는 아래와 같이

그리고 FormClosing에 반대 일을

protected override OnLoad(EventArgs e) 
{ 
    base.OnLoad(e); 

    var doc = XDocument.Load("path/to/xml/file"); 
    foreach(var element in doc.Descendant("PictureBoxes").Elements()) 
    { 
     var pb = new PictureBox(); 
     pb.Name = element.Name.LocalName; 
     pb.Size.Width = Convert.ToInt32(element.Element("SizeWidth").Value)); 
     // other properties here 
     this.Controls.Add(pb); 
    } 
} 
- 그림 상자를 반복하고 XML의 속성을 저장

protected override void OnFormClosing(FormClosingEventArgs e) 
{ 
    base.OnFormClosing(e); 

    var doc = new XDocument(); 
    doc.Add(new XElement("PictureBoxes", 
     this.Controls.Where(c => c.GetType() == typeof(PictureBox)) 
      .Select(pb => new XElement(pb.Name, 
       new XElement("SizeWidth", pb.Size.Width), 
       new XElement("location", pb.Location.X))))); 
    doc.Save("path/to/xml/file"); 
} 
+0

고마워,하지만 어떻게 부모 노드의 이름을 얻을 수 있습니까? ''노드. – crimson589

+0

nvm, 알겠습니다. 그것은'element.Name.LocalName'입니다. – crimson589