2013-07-05 275 views
1

如何在我的XML文件中選擇特定節點?閱讀特定XML節點

在我的第一foreach我選擇每Property是我Properties標籤裏面,但我希望有一個特定的Property。例如,具有<PropertyCode>的等於123。

XML

<Carga> 
    <Properties> 
     <Property> 
      <PropertyCode>122</PropertyCode> 
      <Fotos> 
       <Foto> 
       </Foto> 
      </Fotos> 
     </Property> 
     <Property> 
      <PropertyCode>123</PropertyCode> 
      <Fotos> 
       <Foto> 
       </Foto> 
      </Fotos> 
     </Property> 
    </Properties> 
</Carga> 

C#代碼

// Here I get all Property tag 
// But i want to take just a specific one 
foreach (XmlElement property in xmldoc.SelectNodes("/Carga/Properties/Property")) 
{ 
    foreach (XmlElement photo in imovel.SelectNodes("Fotos/Foto")) 
    { 
     string photoName = photo.ChildNodes.Item(0).InnerText.Trim(); 
     string url = photo.ChildNodes.Item(1).InnerText.Trim(); 
     this.DownloadImages(property_id, url, photoName); 
    } 
} 

有人能幫助我嗎?

回答

3

使用Linq to Xml

int code = 123; 
var xdoc = XDocument.Load(path_to_xml); 
var property = xdoc.Descendants("Property") 
        .FirstOrDefault(p => (int)p.Element("PropertyCode") == code); 

if (property != null) 
{ 
    var fotos = property.Element("Fotos").Elements().Select(f => (string)f); 
} 

fotos將字符串的集合。

+0

用'XMLDocument'能我這樣做? –

+0

@Lucas_Santos你可以,但你爲什麼? Linq to Xml給你很好的強類型解析 –

+0

在第一時刻,我想用'XMLDocument'來工作,因爲我的XML文件比我放的這個樣本大得多。所以,當我更新我的應用程序的版本時,我可以更改爲'XDocument' –

1

可以使用謂詞表達你的XPath挑選出特定節點的..這樣的事情:

XmlNodeList nl = xmldoc.SelectNodes("/Carga/Properties/Property[PropertyCode='123']/Fotos/Foto"); 
foreach(XmlNode n in nl) { ... } 

看到這裏的快速參考XPath語法:http://www.w3schools.com/xpath/xpath_syntax.asp

+0

+1好得多,但我寧願使用XPath擴展的XDocument –