简体   繁体   English

读取特定的XML节点

[英]Read specific XML node

How can I select a specific node in my XML file ? 如何在XML文件中选择特定节点?

In my first foreach I select every Property that are inside my Properties tag, but I want a specific Property . 在我的第一个foreach我选择了我的Properties标签内的每个Property ,但我想要一个特定的Property A Property that has the <PropertyCode> equals 123 for example. Property具有<PropertyCode>等于123例如。

XML XML

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

C# Code 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 );
   }
}

Someone can help me? 有人可以帮帮我吗?

Use Linq to Xml : 使用Linq到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 will be collection of strings. fotos将是字符串的集合。

You can use a predicate expression in your XPath to pick out specific nodes.. something like this: 您可以在XPath中使用谓词表达式来选择特定节点。这样的事情:

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

See here for a quick reference to XPath syntax: http://www.w3schools.com/xpath/xpath_syntax.asp 有关XPath语法的快速参考,请参见此处: http//www.w3schools.com/xpath/xpath_syntax.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM