gpt4 book ai didi

c# - Linq to XML - 查找元素

转载 作者:数据小太阳 更新时间:2023-10-29 01:50:30 24 4
gpt4 key购买 nike

我确信这是基本的,之前可能有人问过,但我才刚刚开始使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com