【问题标题】:Get value of an Xml attribute using Linq to Xml使用 Linq to Xml 获取 Xml 属性的值
【发布时间】:2015-03-12 07:47:25
【问题描述】:

我有一个这样的 XML:

<?xml version="1.0" encoding="utf-8"?>
<Projects>
  <Project>
    <Name>Projekt0</Name>
    <Information>
      <Version>1.0</Version>
      <Info>test-project</Info>
      <CreateDate>25.02.2015</CreateDate>
    </Information>
    <Files ID="1" path="D:\Data\ID1">
      <file>one_file</file>
      <file>another_file</file>
    </Files>
    <Files ID="2" path="D:\Data\ID2">
      <file>someFile.txt</file>
    </Files>
  </Project>
</Projects>

它包含更多“项目”-节点,但这不是必需的。

首先,我通过名称选择一个特定项目。这已经有效,并且以这种方式完成:

var entries = from items in xelement.Elements("Project")
                      where (string)items.Element("Name").Value == projectName
                      select items;

entries 现在包含所需项目的所有内容。

我的一种方法需要知道两个“文件”节点的路径值。 我已经尝试了一些东西,但它还没有工作。

我的第一次尝试是创建一个新的“var”,如“entries”,将其转换为数组,然后选择索引以将值保存为字符串。

var path1 = from item in entries.Elements("Files")
            where (string)item.Attribute("ID").Value == "1"
            select item.Attribute("path").Value;
string path01 = path1.toArray()[0];

这不起作用,我不知道为什么。如果这是一个初学者的问题,我很抱歉,但我还没有对 xml 和 linq 做过很多。

编辑:

较低的“条目”变量是第一个 linq 代码的输出。所以“条目”包含一个完整的项目。 目前,path1 不包含任何元素。

【问题讨论】:

  • 您能否解释一下“这不起作用”是什么意思?
  • 第二个entries和第一个entries变量一样吗?如果是这样,它包含项目元素和这些元素没有属性ID

标签: c# xml linq linq-to-xml


【解决方案1】:

entries 是一系列项目节点。在搜索 ID 属性之前获取 Files 子节点

var path1 = from item in entries.Elements("Files")
        where (string)item.Attribute("ID").Value == "1"
        select item.Attribute("path").Value;

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 2013-01-10
    • 2013-04-02
    • 2016-06-10
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多