2013-07-05 193 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 –