c# - 读取特定的 XML 节点

标签 c#

如何在我的 XML 中选择特定节点文件?

在我的第一个foreach我选择每个 Property在我的里面 Properties标签,但我想要一个特定的 Property . 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 );
   }
}

有人可以帮助我吗?

最佳答案

使用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 将是字符串的集合。

关于c# - 读取特定的 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17491283/

相关文章:

c# - Xcode Cocoa - 从 NSTableView 拖放到 Finder

c# - 这是什么颜色代码?

c# - 使用 C# sdk/api 将歌曲添加到 iTunes

c# - 无法从 C# 向 mysql DB 插入日期

c# - 将值从字符串解析为未知变量类型

c# - 如何使标签在 WinForms 中居中?

C# Httpclient FormUrlEncodedContent 编码

c# - 使用 EF 从 Azure 移动服务检索父/子记录(包含列表的对象)

c# - 如何将对象序列化为 Json,在桌面 C# 应用程序中将对象类的名称作为根添加?

c# - 无法按名称或路径删除图像文件