c# - Linq to XML - 查找元素

标签 c# xml linq linq-to-xml

我确信这是基本的,之前可能有人问过,但我才刚刚开始使用 Linq to XML。

我有一个简单的 XML 需要读取和写入。

<Documents>
...
    <Document>
      <GUID>09a1f55f-c248-44cd-9460-c0aab7c017c9-0</GUID>
      <ArchiveTime>2012-05-15T14:27:58.5270023+02:00</ArchiveTime>
      <ArchiveTimeUtc>2012-05-15T12:27:58.5270023Z</ArchiveTimeUtc>
      <IndexDatas>
        <IndexData>
          <Name>Name1</Name>
          <Value>Some value</Value>
          <DataType>1</DataType>
          <CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime>
          <CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc>
        </IndexData>
        <IndexData>
          <Name>Name2</Name>
          <Value>Some value</Value>
          <DataType>3</DataType>
          <CreationTime>2012-05-15T14:27:39.6427753+02:00</CreationTime>
          <CreationTimeUtc>2012-05-15T12:27:39.6427753Z</CreationTimeUtc>
        </IndexData>
   ...
 </IndexDatas>
</Document>
...
</Documents>

我有一个“文档”节点,其中包含一堆“文档”节点。

我有文档的 GUID 和一个“IndexData”名称。 我需要通过 GUID 找到文档并检查它是否有带有某个名称的“IndexData”。 如果没有,我需要添加它。

任何帮助都将不胜感激,因为我在阅读和搜索元素时遇到问题。

目前我正在尝试使用(在 C# 中):

IEnumerable<XElement> xmlDocuments = from c in XElement
                                        .Load(filePath)
                                        .Elements("Documents") 
                                         select c;

// fetch document
 XElement documentElementToEdit = (from c in xmlDocuments where 
                    (string)c.Element("GUID").Value == GUID select c).Single();

编辑

xmlDocuments.Element("Documents").Elements("Document")

这不会返回任何结果,即使 xmlDocuments.Element("Documents") 会返回结果。看起来我无法从文档节点获取文档节点。

最佳答案

您可以使用以下代码找到那些文档(索引数据中没有相关名称的文档),之后您可以将元素添加到 IndexData 元素的末尾。

var relatedDocs = doc.Elements("Document")
   .Where(x=>x.Element("GUID").Value == givenValue)
   .Where(x=>!x.Element("IndexDatas")
              .Elements("IndexData")
              .Any(x=>x.Element("Name") == someValue);

关于c# - Linq to XML - 查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11356895/

相关文章:

linq - 带有 Select 的 Task.WhenAll 是一把枪——但为什么呢?

c# - 在加载应用程序目录之外的目录中加载依赖于其他程序集的程序集?

C# 线程 : Console application in new thread is invisible

java - 带有 Fragment 和 ViewPager 的 NullPointerException

php - DOMElement 克隆和追加 : 'Wrong Document Error'

java - 从 XSD 获取完整的 XML 结构

c# - 通过 LINQ 从另一个列表中过滤一个列表 <string>

C# Linq 语句或用于总计子集的 foreach()?

c# - 线程安全 List<T>.Remove 创建的 System.ArgumentOutOfRangeException

c# - 数组中有多少元素不为空?